From f143fb3d744e21e68154f382c21ee8058a89be06 Mon Sep 17 00:00:00 2001 From: Elder Henrique Souza Date: Thu, 14 Dec 2017 12:57:03 -0200 Subject: [PATCH] minor refactor to group by --- snippets/group-by.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/snippets/group-by.md b/snippets/group-by.md index ab833c9d2..44505eb2f 100644 --- a/snippets/group-by.md +++ b/snippets/group-by.md @@ -5,10 +5,9 @@ Use `Array.reduce()` to create an object, where the keys are produced from the m ```js const groupBy = (arr, func) => - (typeof func === 'function' ? arr.map(func) : arr.map(val => val[func])) - .reduce((acc, val, i) => { - acc[val] = acc[val] === undefined ? [arr[i]] : acc[val].concat(arr[i]); return acc; - }, {}); + arr + .map(typeof func === 'function' ? func : val => val[func]) + .reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}) // groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]} // groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']} ```