From ea3942210c838d7a1e9206445ad490b0240a55dc Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Mon, 8 Jan 2018 16:58:23 +0200 Subject: [PATCH] Add partition --- snippets/partition.md | 19 +++++++++++++++++++ tag_database | 1 + 2 files changed, 20 insertions(+) create mode 100644 snippets/partition.md diff --git a/snippets/partition.md b/snippets/partition.md new file mode 100644 index 000000000..872308aae --- /dev/null +++ b/snippets/partition.md @@ -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 }]] +``` diff --git a/tag_database b/tag_database index a9862093d..c581d0f0f 100644 --- a/tag_database +++ b/tag_database @@ -111,6 +111,7 @@ once:function onUserInputChange:browser,event,advanced orderBy:object,array palindrome:string +partition:array,object,function percentile:math pick:array pipeFunctions:adapter,function