Skip to content

Instantly share code, notes, and snippets.

@neharkarvishal
Last active December 25, 2019 10:29
Show Gist options
  • Save neharkarvishal/bfe6aef2022b625f262522d700608e4d to your computer and use it in GitHub Desktop.
Save neharkarvishal/bfe6aef2022b625f262522d700608e4d to your computer and use it in GitHub Desktop.
/**
* 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) );
@neharkarvishal
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment