Skip to content

Commit e037714

Browse files
Added a snippet to split an array into two arrays based on a callback function
1 parent f1f3b6a commit e037714

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
---
2+
title: Partition Array
3+
description: Splits an array into two arrays based on a callback function.
4+
author: Swaraj-Singh-30
5+
tags: javascript,array,partition,reduce,utility
6+
---
7+
8+
```js
9+
const partition = (arr, callback) =>
10+
arr.reduce(
11+
([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),
12+
[[], []]
13+
);
14+
15+
// Usage:
16+
const numbers = [1, 2, 3, 4, 5, 6];
17+
const isEven = (n) => n % 2 === 0;
18+
console.log(partition(numbers, isEven)); // Output: [[2, 4, 6], [1, 3, 5]]
19+
```

0 commit comments

Comments
 (0)