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?
What about this?
Probably this is more efficient then the spread operator
Or a bit shorter, but uglier
In filter function you can push your false items into another variable outside function:
Of course
value === false
need to be real comparasion ;)But it do almost that same operation like
forEach
. I think you should useforEach
for better code readability.I ended up doing this because it's easy to understand (and fully typed with typescript).
I came up with this little guy. It uses for each and all that like you described, but it looks clean and succinct in my opinion.
With ES6 you can make use of the spread syntax with reduce:
Or on a single line:
Try this:
DEMO