Use "Array.prototype.filter" to list what you do and what is not part of the condition

Asked

Viewed 107 times

2

Is there any way to make one filter in an array and retrieve what it does and what is not part of the condition?

For example the following object:

{
  "data": [
    { "item": 1 },
    { "item": 2 },
    { "item": 3 },
    { "item": 4 },
    { "item": 5 },
    { "item": 6 }
  ]
}

Return a result of type:

{
  "conditionTrue": [
    { "item": 1 },
    { "item": 2 },
    { "item": 3 }
 ],
"conditionFalse": [
    { "item": 4 },
    { "item": 5 },
    { "item": 6 }
  ]
}

Filtering in the following way I can obtain the elements of the true case and those of the negative case:

a = {"data":[{"item":1},{"item":2},{"item":3},{"item":4},{"item":5},{"item":6}]};

a.data.filter(el => [1,2,3].includes(el.item));
// [{"item":1},{"item":2},{"item":3}]
a.data.filter(el => ![1,2,3].includes(el.item));
// [{"item":4},{"item":5},{"item":6}]

However, I wanted to make only one filter to obtain the condition if true and if negative.

I tried to do something like the following, but it didn’t work.

a = {"data":[{"item":1},{"item":2},{"item":3},{"item":4},{"item":5},{"item":6}]};

a.data.filter(el => {
  return {
    conditionTrue: [1, 2, 3].includes(el.item),
    conditionFalse: ![1, 2, 3].includes(el.item)
  }
});

2 answers

2

This example does not use filter(), uses reduce():

let a = {
    "data":
        [
            { "item": 1 },
            { "item": 2 },
            { "item": 3 },
            { "item": 4 },
            { "item": 5 },
            { "item": 6 }
        ]
};

let sample = [1, 2, 3];

let result = a.data.reduce((acc, cur) => {
    let key = (sample.includes(cur.item)) ? 'conditionTrue' : 'conditionFalse';
    acc[key] = acc[key] || [];    
    acc[key].push(cur);
    return acc;
}, {});

console.log(result);

2


No. Javascript does not have this implementation natively, but nothing prevents you from doing a:

function filter(array, cb) {
  if (typeof cb !== 'function') {
    throw new TypeError('Invalid `cb` argument.');
  }

  const filteredValues = [];
  const removedValues = [];

  for (const [index, value] of array.entries()) {
    const test = !!cb(value, index, array);

    if (test) {
      filteredValues.push(value);
    } else {
      removedValues.push(value);
    }
  }

  return [filteredValues, removedValues];
}

// Irá remover os ímpares, mantendo somente os pares:
const [filteredValues, removedValues] = filter(
  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
  (el) => el % 2 === 0
);

console.log('Valores mantidos:', filteredValues);
console.log('Valores removidos:', removedValues);

This is just one of the ways to do it. Use it as an idea to create something even better. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.