简体   繁体   中英

Recreating underscore.js 'reject' using 'filter'

I have a project which requires me to replicate underscore.js's 'reject' function using the 'filter' function. I've written the following, though can't seem to get the tests to pass. Any suggestions?

// Return all elements of an array that pass a truth test.
  _.filter = function(collection, test) {
    var passed = [];
    _.each(collection, function(item, index) {
      if (test(item) === true) {
        passed.push(item);
      }
    });
    return passed;
  };

  // Return all elements of an array that don't pass a truth test.
  _.reject = function(collection, test) {
    _.filter(collection, function(item) {
      return !test(item);
    });
  };

You forgot to return the result of filter .

_.reject = function(collection, test) {
  return _.filter(collection, function(item) {
    return !test(item);
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM