Javascript Array filter(predicate)

Description

Javascript Array filter(predicate)


'use strict';/* w ww . java  2 s  .c o  m*/

Array.prototype.filter = function (predicate) {
    var results = [];
    this.forEach(function (element) {
        if (predicate(element)) results.push(element)
    });
    return results;
};

Javascript Array filter(predicate)

Array.prototype.filter = function(predicate) {
 var result = []//  www.  j  a va 2s. co m
 for ( var i = 0; i < this.length; i++) {
  if (predicate(this[i])) {
   result.push(this[i]);
  }
 }
 return result;
}

Javascript Array filter(predicate)

Array.prototype.filter = function(predicate){
 return this.reduce(function(accumulator, value){
  return predicate(value) ? accumulator.concat(value) : accumulator;
 }, []);/*w w  w  . j  a  v  a2s .  com*/
}

console.log([1, 2, 3, 4, 5].filter(function(val){
 return val % 2 === 0; 
}));

//console.log([1, 2, 3, [4, 5, 6], [7, 8, [9, 10, [11, 12]]], 13 ].flatten())



PreviousNext

Related