Javascript Array filter(cb)
/* filter method */ Array.prototype.filter = function(cb) { var result = [], i= 0;//from w ww . j a va 2s .c om for(i; i<this.length; i++) { var isTrue = cb(this[i]); if(isTrue === true) { result.push(this[i]) } } return result; } var foo = [0, 1, 5, 40, 584, 3984, 5]; var filtered = foo.filter(function(value){ return value < 10; }); console.log(filtered); // [ 0, 1, 5, 5 ]
//Implement filter function for Array Array.prototype.filter = function(cb){ var arr = Object(this); var res = []; for(var i=0;i<arr.length;i++){ if(cb(arr[i])){ res.push(arr[i]);//www.j a va2 s. c om } } return res; }