QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Partition Array

Splits an array into two arrays based on a callback function.

  • array
  • partition
  • reduce

Install

npx shadcn@latest add https://quicksnip.dev/r/partition-array.json

This snippet is not verified yet. Review it before use, or help verify it.

Code

const partition = (arr, callback) =>
  arr.reduce(
    ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),
    [[], []]
  );

Usage

const numbers = [1, 2, 3, 4, 5, 6];
const isEven = (n) => n % 2 === 0;
partition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]