Filter with remaining `Array.propotype.filterWithRemaining()`

I would like to make a proposal for Filter with Remaining, and am seeking some feedback from the community. Feel free to suggest name changes, flaws, other possible solutions.

Filter with remaining

Introduce a feature which additionally to filtered results, returns the unfiltered or remaining items in an array.

Array.prototype.filter(callbackFN, {remaing: true}, thisArg)] Array.prototype.filterWithRemaining()

Motivation

There are times where one needs to filter results and need to handle the remaining unfiltered results for some other purposes aswell. This could be achieved, in a round about way, doing an additional iteration with the inverted filter condition. This feature would return the filtered and remaing in the same array iteration.

Example

const [filteredArray, remainingArray] = [1,2,3,4,5].filterWithRemaining( num => num % 2);

console.log(filteredArray) // [2,4]
console.log(remainingArray) // [1,3,5]

Alternatively we could make a optional parameter to the filter method.

const [filteredArray, remainingArray] = [1,2,3,4,5].filter( num => num % 2, {remaining: true})

See the following array.group proposal, which seems like it'll provide the functionality you need: GitHub - tc39/proposal-array-grouping: A proposal to make grouping of array items easier

Example:

const { true: filteredArray, false: remainingArray } = [1,2,3,4,5].group( num => num % 2);

console.log(filteredArray) // [2,4]
console.log(remainingArray) // [1,3,5]
3 Likes

This is commonly implemented as partition(). A discussion about this was brought up in the filterReject() proposal (a method giving you just the remaining) and that can be found here:

It started in the filterReject repo but then jumped over to group so we have two links for it :upside_down_face:.

2 Likes

Thanks for pointing that out! I see group is more flexible. I'm excited to try it out :cowboy_hat_face: