minor refactor to group by

This commit is contained in:
Elder Henrique Souza
2017-12-14 12:57:03 -02:00
committed by GitHub
parent 61dc0394df
commit f143fb3d74

View File

@ -5,10 +5,9 @@ Use `Array.reduce()` to create an object, where the keys are produced from the m
```js ```js
const groupBy = (arr, func) => const groupBy = (arr, func) =>
(typeof func === 'function' ? arr.map(func) : arr.map(val => val[func])) arr
.reduce((acc, val, i) => { .map(typeof func === 'function' ? func : val => val[func])
acc[val] = acc[val] === undefined ? [arr[i]] : acc[val].concat(arr[i]); return acc; .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([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']} // groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}
``` ```