hyang123
hyang123

Reputation: 1280

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?

Upvotes: 0

Views: 2687

Answers (5)

chrisz
chrisz

Reputation: 1401

  • 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]

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386746

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);

Upvotes: 0

castletheperson
castletheperson

Reputation: 33496

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);

Upvotes: 2

Jared Smith
Jared Smith

Reputation: 22014

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.

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 192507

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);

Upvotes: 1

Related Questions