Last active
December 25, 2019 10:29
-
-
Save neharkarvishal/bfe6aef2022b625f262522d700608e4d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* partitionArray.js | |
* tags: { JavaScript, Array, Object, Function } | |
* Groups the elements into two arrays, depending on the provided function's | |
* truthiness for each element. | |
* Use Array.prototype.reduce() to create an array of two arrays. | |
* Use Array.prototype.push() to add elements for which fn returns true to the | |
* first array and elements for which fn returns false to the second one. | |
*/ | |
const partition = (arr, fn) => | |
arr.reduce( | |
(acc, val, i, arr) => { | |
acc[fn(val, i, arr) ? 0 : 1].push(val); | |
return acc; | |
}, | |
[[], []] | |
); | |
const users = [ | |
{ user: "dave", age: 19, active: false }, | |
{ user: "fred", age: 20, active: true } | |
]; | |
// [ | |
// [{ 'user': 'fred', 'age': 20, 'active': true }], | |
// [{ 'user': 'dave', 'age': 19, 'active': false }] | |
// ] | |
console.log( partition(users, o => o.active) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
partitionArray.js
tags: { JavaScript, Array, Object, Function }
Groups the elements into two arrays, depending on the provided function's
truthiness for each element.
Use
Array.prototype.reduce()
to create an array of two arrays.Use
Array.prototype.push()
to add elements for whichfn
returns true to thefirst array and elements for which
fn
returns false to the second one.