Skip to content

Commit 4247224

Browse files
Merge pull request #114 from Swaraj-Singh-30/main
Added a snippet for partitioning arrays with a callback
2 parents 8e2e05c + 452f2a1 commit 4247224

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

public/consolidated/javascript.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1018,4 +1018,4 @@
10181018
}
10191019
]
10201020
}
1021-
]
1021+
]
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)