mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
24 lines
395 B
JavaScript
24 lines
395 B
JavaScript
|
/**
|
||
|
* @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]}
|
||
|
*/
|