Files
30-seconds-of-code/snippets/bifurcate.md
Isabelle Viktoria Maciohsek 2b6f2b1740 Update snippet descriptions & tags
2020-10-18 23:04:45 +03:00

20 lines
606 B
Markdown

---
title: bifurcate
tags: array,intermediate
---
Splits values into two groups, based on the result of the given `filter` array.
- Use `Array.prototype.reduce()` and `Array.prototype.push()` to add elements to groups, based on `filter`.
- If `filter` has a truthy value for any element, add it to the first group, otherwise add it to the second group.
```js
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
```
```js
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]);
// [ ['beep', 'boop', 'bar'], ['foo'] ]
```