Skip to content

Commit eee2982

Browse files
committed
2631. Group By
1 parent 21fb8ae commit eee2982

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

Group By/kata.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @param {Function} fn
3+
* @return {Object}
4+
*/
5+
Array.prototype.groupBy = function(fn) {
6+
let groups = {}
7+
this.forEach((element, index) => {
8+
const key = fn(element)
9+
if (groups[key]) {
10+
groups[key].push(element)
11+
} else {
12+
groups[key] = []
13+
groups[key].push(element)
14+
}
15+
})
16+
return groups
17+
};
18+
19+
/**
20+
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
21+
*/

0 commit comments

Comments
 (0)