Created
September 19, 2011 11:34
-
-
Save ishiduca/1226332 to your computer and use it in GitHub Desktop.
Array#grep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// javascript 1.6 以上だと filteredArray = array.filter(callback[, thisObject]) を使うといい。 | |
// 使えない場合に grep を実装する | |
// | |
// var FuncOfGrepRule = function (itemOfArray) { | |
// return (itemOfArray.match(/condition/)) ? true : false; | |
// }); | |
// | |
// var newArray = orgArray.grep(FuncOfGrepRule); | |
// | |
if (! Array.prototype.grep) { | |
Array.prototype.grep = function (func) { | |
if (typeof func !== 'function') throw new Error('1st argument must be "function"'); | |
var that = this.slice(0), len = that.length; | |
for (len--; len >= 0; len--) { | |
if (! func(that[len], len)) that.splice(len, 1); | |
} | |
return (that.length === 0) ? undefined : that; | |
}; | |
} | |
var org = ("pretty dog prenty doll home drug github ben harper").split(/\s+/); | |
console.log('元の配列'); | |
console.log(JSON.stringify(org)); | |
var greped = org.grep(function (_item) { | |
return (_item.match(/do/i)); | |
}); | |
console.log('grepした配列'); | |
console.log(JSON.stringify(greped)); | |
console.log('元の配列'); | |
console.log(JSON.stringify(org)); | |
var ORG = [ | |
{ mak : 'abc' }, | |
{ mak : 'def' }, | |
{ mak : 'GHI' }, | |
{ mak : 'JKL' } | |
]; | |
var GREPED = ORG.grep(function (hash) { | |
return (hash['mak'].match(/e|h/i)); | |
}); | |
console.log(JSON.stringify(GREPED)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment