Group By
LeetCode題目: 2631. Group By
My solution:
/**
* @param {Function} fn
* @return {Object}
*/
Array.prototype.groupBy = function(fn) {
let groups = {};
for(let item of this) {
const key = fn(item);
groups[key] ? groups[key].push(item) : groups[key] = [item];
}
return groups;
};
/**
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
*/