Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the excluded elements when using javascript's filter

Javascript's filter returns the array with all the elements passing the test.

How how can you easily get all the elements that failed the test without running the test again, but for the converse? How is the best way to do it, even if you have to run the test again.

let arr; // this is the array on which the filter will be run [SET ELSEWHERE]
let fn; // The filter function [SET ELSEWHERE]
let goodElements; // This will be the new array of the good elements passing the test
let badElements; // This will be the new array of the elements failing the test

goodElements = arr.filter(fn);

// SO HOW IS badElements set????

How is badElements set?

like image 324
Rewind Avatar asked Apr 24 '26 03:04

Rewind


2 Answers

If you don't want to do two iterations, you can use a for loop and a ternary operator:

let arr = [1, 2, 3];
let fn = (e) => e % 2 == 0;
let goodElements = [];
let badElements = [];

for(const e of arr) (fn(e) ? goodElements : badElements).push(e);
console.log(goodElements);
console.log(badElements);

Otherwise, just invert the condition with the ! operator:

let arr = [1, 2, 3];
let fn = (e) => e % 2 == 0;
let goodElements;
let badElements;

goodElements = arr.filter(fn);
badElements = arr.filter(e => !fn(e));
console.log(goodElements);
console.log(badElements);
like image 180
Spectric Avatar answered Apr 26 '26 16:04

Spectric


Don't use filter(). If you want to partition the data into two arrays, do it yourself.

function partition(array, fn) {
  let goodArray = [],
    badArray = [];
  array.forEach(el => {
    if (fn(el)) {
      goodArray.push(el);
    } else {
      badArray.push(el);
    }
  });
  return [goodArray, badArray];
}

let [goodElemements, badElements] = partition(arr, fn);

You could also use reduce()

function partition(array, fn) {
  return array.reduce(acc, el => {
    if (fn(el)) {
      acc[0].push(el);
    } else {
      acc[1].push(el);
    }
  }, [[],[]]);
}

let [goodElemements, badElements] = partition(arr, fn);
like image 34
Barmar Avatar answered Apr 26 '26 16:04

Barmar