Partition array in two

OSCC · JavaScript, Array, Object · Nov 3, 2020

Groups the elements into two arrays, depending on the provided function's truthiness for each element.

const partition = (arr, fn) =>
  arr.reduce(
    (acc, val, i, arr) => {
      acc[fn(val, i, arr) ? 0 : 1].push(val);
      return acc;
    },
    [[], []]
  );
const users = [
  { user: 'barney', age: 36, active: false },
  { user: 'fred', age: 40, active: true },
];
partition(users, o => o.active);
// [
//   [{ user: 'fred', age: 40, active: true }],
//   [{ user: 'barney', age: 36, active: false }]
// ]

Recommended snippets

  • Partition array

    JavaScript, Array

    Applies fn to each value in arr, splitting it each time the provided function returns a new value.

  • Count grouped elements

    JavaScript, Array

    Groups the elements of an array based on the given function and returns the count of elements in each group.

  • Returns the symmetric difference between two arrays, after applying the provided function to each array element of both.