JavaScript算法题(二) && 数组filter使用

1.Let's implement the reject() function...

例: 

var odds = reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [1, 3, 5]

soluction:

function reject(array, iterator) {
    return array.filter(function(x){return !iterator(x)})
}

2.The numberOfOccurrences function must return the number of occurrences of an element in an array.

例:

var arr = [0,1,2,2,3];
arr.numberOfOccurrences(0) === 1;
arr.numberOfOccurrences(4) === 0;
arr.numberOfOccurrences(2) === 2;
arr.numberOfOccurrences("a") === 0;

soluction:

Array.prototype.numberOfOccurrences = function() {
  return this.filter( function(num){ return search === num } ).length;
}
原文地址:https://www.cnblogs.com/showtime813/p/4466398.html