Add partition

This commit is contained in:
Angelos Chalaris
2018-01-08 16:58:23 +02:00
parent ef884c666b
commit 975b83903d
2 changed files with 20 additions and 0 deletions

19
snippets/partition.md Normal file
View File

@ -0,0 +1,19 @@
### partition
Groups the elements into two arrays, depending on the provided function's truthiness for each element.
Use `Array.reduce()` to create an array of two arrays.
Use `Array.push()` to add elements for which `fn` returns `true` to the first array and elements for which `fn` returns `false` to the second one.
```js
const partition = (arr, fn) =>
arr.reduce((acc, val, i, arr) => {fn(val,i,arr) ? acc[0].push(val) : acc[1].push(val); return acc;},[[],[]]);
```
```js
var 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 }]]
```