problems(js): add “2631. Group By”
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
817d40aa95
commit
d0a6ab210b
1 changed files with 23 additions and 0 deletions
23
problems/js/group-by.js
Normal file
23
problems/js/group-by.js
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
/**
|
||||||
|
* @param {Function} fn
|
||||||
|
* @return {Array}
|
||||||
|
*/
|
||||||
|
Array.prototype.groupBy = function(fn) {
|
||||||
|
let grouped = new Object();
|
||||||
|
|
||||||
|
for (let x of this) {
|
||||||
|
let key = fn(x);
|
||||||
|
|
||||||
|
if (grouped[key] === undefined) {
|
||||||
|
grouped[key] = new Array();
|
||||||
|
}
|
||||||
|
|
||||||
|
grouped[key].push(x);
|
||||||
|
}
|
||||||
|
|
||||||
|
return grouped;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
|
||||||
|
*/
|
Loading…
Reference in a new issue