Javascript Array filter(predicateFunction)

Description

Javascript Array filter(predicateFunction)


Array.prototype.filter = function(predicateFunction) {
  var results = [];
  this.forEach(function(itemInArray) {
    if (predicateFunction(itemInArray)) {
    results.push(itemInArray);/* w w w  .  j  av  a2 s. co m*/
    }
  });

  return results;
};

Javascript Array filter(predicateFunction)

Array.prototype.filter = function(predicateFunction) {
 var results = [];
 this.forEach(function(itemInArray) {
    if(itemInArray > 2) {results.push(itemInArray)}

 });//from w w  w .j  av a 2  s.c o m

 return results;
};

Javascript Array filter(predicateFunction)

//http://reactivex.io/learnrx/
//Exercise 7: Implement filter()
//To make filtering easier, let's add a filter() function to the Array type. The filter() function accepts a predicate. A predicate is a function that accepts an item in the array, and returns a boolean indicating whether the item should be retained in the new array.
Array.prototype.filter = function(predicateFunction) {
 var results = [];
  this.forEach(function(itemInArray) {
    if (predicateFunction(itemInArray)) {
    results.push(itemInArray);/*from  w ww. ja v  a 2s  . c om*/
    }
  });
  return results;
};

console.log(JSON.stringify([1,2,3].filter(function(x) { return x > 2})));// === "[3]"



// JSON.stringify([1,2,3].filter(function(x) { return x > 2})) === "[3]"

Javascript Array filter(predicateFunction)

/**/*w ww .  ja v  a2  s .c  o  m*/
 * IMPLEMENT FILTER
 * Ex.7: IMPLEMENTING ON A PROTOTYPE
 * Notice that, like map(), every filter() operation shares some operations in common:
1. Traverse the array
2. Add objects that pass the test to a new array
Why not abstract away how these operations are carried out?
*/

/**
 * @TODO: Implement filter on a prototype
 * Process:
 * 1. add filter function to the array type
 * 2. Include the predicate to filter the array
 */

Array.prototype.filter = function (predicateFunction) {
  var results = [];
  this.forEach(function (itemInArray) {
    if (predicateFunction(itemInArray)) {
      results.push(itemInArray);
    }
  });
  console.log(results);
  return results;
};

JSON.stringify([1, 2, 3].filter(function (x) { return x > 2 })) === "[3]"



PreviousNext

Related