const partition = (arr, fn) =>
arr.reduce(
(acc, val, i, arr) => {
acc[fn(val, i, arr) ? 0 : 1].push(val);
return acc;
},
[[], []]
);
const partitionBy = (arr, fn) =>
arr.reduce(
({ res, last }, v, i, a) => {
const next = fn(v, i, a);
if (next !== last) res.push([v]);
else res[res.length - 1].push(v);
return { res, last: next };
},
{ res: [] }
).res;
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 }]
// ]
const numbers = [1, 1, 3, 3, 4, 5, 5, 5];
partitionBy(numbers, n => n % 2 === 0); // [[1, 1, 3, 3], [4], [5, 5, 5]]
partitionBy(numbers, n => n); // [[1, 1], [3, 3], [4], [5, 5, 5]]
Массивы и объекты JavaScript
JavaScript