repl.it
JavaScript

Implementation of the underscore reject method

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
reject = function (collection, predicate, context) {
  var result = [];

  if (Object.prototype.toString.call(collection) == '[object Object]') {
    for (var key in collection) {
      if (collection.hasOwnProperty(key)) {
        if (!predicate.call(context, collection[key], key, collection)) {
          result.push(collection[key]);
        }
      }
    }
  } else {
    for (var i = 0; i < collection.length; i++) {
      if (!predicate.call(context, collection[i], i, collection)) {
        result.push(collection[i]);
      }
    }
  }

  return result;
};

var list = [1,2,3,4,5,6,7,8,9,10];
var odd = reject(list, item => {
	return item % 2 === 0;
})

var nums = [20, 40, 50, 60, 80]
var largeNums = reject(nums, num => {
	return num <= 40;
})

console.log(odd);
// => [ 1, 3, 5, 7, 9 ]

console.log(largeNums);
// => [ 50, 60, 80 ]
Native Browser JavaScript