— partition is a function from the Lodash library.
What _.partition does
.partition(collection, predicate)
- Takes an array (collection) and a predicate function (a condition).
- Splits the array into two sub-arrays:
- First array → all elements where the predicate returns true
- Second array → all elements where the predicate returns false
- Returns them as a 2-element array: [matches, nonMatches].
Example
const assets = [
{ name: 'iPhone', assetType: 'Device' },
{ name: 'Netflix', assetType: 'Subscription' },
{ name: 'iPad', assetType: 'Device' }
];
const [devices, subs] = _.partition(
assets,
asset => asset.assetType === 'Device'
);
console.log(devices);
// [{ name: 'iPhone', assetType: 'Device' }, { name: 'iPad', assetType: 'Device' }]
console.log(subs);
// [{ name: 'Netflix', assetType: 'Subscription' }]
Why it’s different from .filter()
If you used .filter() twice like this:
const truthy = arr.filter(x => condition(x));
const falsy = arr.filter(x => !condition(x));
You’d loop through the array two times.
_.partition does it in one loop more efficient.