Just wondering if it's possible to use an array function (like filter) to return both the negative and the positive outcomes of the statement at the same time using destructuring.
Something like the following:
let {truthys, falsys} = arr.filter(a => {
return //magical statement that returns truthy's and falsy's?
});
instead of:
let truthys = arr.filter(item => item.isTruthy);
let falsys = arr.filter(item => !item.isTruthy);
So something of a shorthand-way of doing the latter. Can't seem to find anything about this anywhere so it might not be possible at all. Thanks!
.reduce()to create an object with two arrays..filter()returns one array of values. Doesn't make much sense to destructure it, if you pass a predicate. What you can do is group by the predicate result and return an object with{ "true" : /* items that passed the predicate test */, "false": /* items that did not pass the predicate test */ }and then destructure asconst {true: truthys, false: falsys} = groupedValuespartitionimplementation here it's essentially what you need. You'd call it likeparition(arr, x => !!x)(orparition(arr, Boolean)if you wish). That's partitioning into an array with indexes1and0but the approach is the same if you want to partition into an object with keystrueandfalse. I personally prefer the latter because it's a bit clearer thatresult.trueis the result of everything where the condition returnedtruebut ultimately doesn't matter much.const [thruthys, falsys] = partition(arr, item => item.isTruthy)with an appropriate helper function (see the duplicates) is the standard approach. If you already have agroupByhelper, such as lodash's one, you can also useconst {true: truthys, false: falsys} = _.groupBy(arr, item => !!item.isTruthy).