I have a Javascript array that I would like to split into two based on whether a function called on each element returns true
or false
. Essentially, this is an array.filter
, but I'd like to also have on hand the elements that were filtered out.
Currently, my plan is to use array.forEach
and call the predicate function on each element. Depending on whether this is true or false, I will push the current element onto one of the two new arrays. Is there a more elegant or otherwise better way to do this? An array.filter
where the will push the element onto another array before it returns false
, for instance?
You can use reduce for it:
Update. Using ES6 syntax you also can do that using recursion:
Easy to read one.
This sounds very similar to Ruby's
Enumerable#partition
method.If the function can't have side-effects (i.e., it can't alter the original array), then there's no more efficient way to partition the array than iterating over each element and pushing the element to one of your two arrays.
That being said, it's arguably more "elegant" to create a method on
Array
to perform this function. In this example, the filter function is executed in the context of the original array (i.e.,this
will be the original array), and it receives the element and the index of the element as arguments (similar to jQuery'seach
method):You can use lodash.partition
or ramda.partition