简体   繁体   中英

Make Array.filter() return items which are false instead of true

I will use the example from the MDN Array.prototype.filter() docs.

we can pass decoupled functions into higher order functions like this:

function isBigEnough(value) {
  return value >= 10;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]

Using the example above as reference, is it possible to filter results which are not 'big enough' without defining another decoupled function isSmallEnough() ? In order words, We would like to return [5, 8] .

Can we reuse isBigEnough to achieve this?

You can create a function which returns the inverted form of a function:

 function not(predicate) { return function() { return !predicate.apply(this, arguments); }; } function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(not(isBigEnough)); console.log(filtered); 

Negate the predicate:

 function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(function(value) { return !isBigEnough(value); }); console.log(filtered); 

You could use a wrapper for a not function.

 function isBigEnough(value) { return value >= 10; } var not = fn => (...args) => !fn(...args), filtered = [12, 5, 8, 130, 44].filter(not(isBigEnough)); console.log(filtered); 

Although the existing answers are correct, here's a slightly different take:

let not = x => !x;
let greaterThan = R.curryN(2, (x, y) => y > x);
let greaterThan10 = greaterThan(10); // === isBigEnough
let notGreaterThan10 = R.pipe(greaterThan10, not);

let items = list.filter(notGreaterThan10);

Uses the ramda.js library for composition and currying.

  • I see now this is just an ES6 variation of On Dron's answer. Pretty sure he's right in that this would satisfy the test question.

    Can we reuse isBigEnough to achieve this?

Yes, by slightly modifying your code we can even use the same filter method to return just the false values .

function isBigEnough(value) {
  return value >= 10;
}

var filterFalse = [12, 5, 8, 130, 44].filter(x => !isBigEnough(x));
// filterFalse - [5, 8]

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