1 RN Thing a Day – Day 5: Usage of _partition
Ola Abaza

Ola Abaza @ola_1313

Joined:
Aug 8, 2024

1 RN Thing a Day – Day 5: Usage of _partition

Publish Date: Aug 8
0 0

— 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' }]


Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

You’d loop through the array two times.
_.partition does it in one loop more efficient.

Comments 0 total

    Add comment