I want to get the result of filter()
but also the elements that were removed in the process. For example, I want to get [1]
as a result of the normal filter
operation as well as [2, 3]
in the following execution:
[1, 2, 3].filter(num => num <= 1)
Currently, I’m doing it like this – is there a better and faster way?
function filter() {
const removedNumbers = [];
const newArray = [1, 2, 3].filter((num) => {
if (num > 1) {
removedNumbers.push(num);
return false;
}
return true;
});
return {
newArray,
removedNumbers,
};
}
console.log(filter())
2
Answers
Maybe try
Object.groupBy
, but be aware of its coverage.You can use
Array::reduce()
, seems faster thanObject.groupBy()
.There’s a known problem with the new
flatMap()
that it uses iterators and notoriously slower exactly known 6.2x times.Seems a similar fate befell
Object.groupBy()
: