Skip to content

Commit e794a63

Browse files
committed
Add solution #2631
1 parent e0ed751 commit e794a63

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,7 @@
387387
2627|[Debounce](./2627-debounce.js)|Medium|
388388
2629|[Function Composition](./2629-function-composition.js)|Easy|
389389
2630|[Memoize II](./2630-memoize-ii.js)|Hard|
390+
2631|[Group By](./2631-group-by.js)|Medium|
390391
2634|[Filter Elements from Array](./2634-filter-elements-from-array.js)|Easy|
391392
2635|[Apply Transform Over Each Element in Array](./2635-apply-transform-over-each-element-in-array.js)|Easy|
392393
2637|[Promise Time Limit](./2637-promise-time-limit.js)|Medium|

solutions/2631-group-by.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* 2631. Group By
3+
* https://leetcode.com/problems/group-by/
4+
* Difficulty: Medium
5+
*
6+
* Write code that enhances all arrays such that you can call the array.groupBy(fn) method on any
7+
* array and it will return a grouped version of the array.
8+
*
9+
* A grouped array is an object where each key is the output of fn(arr[i]) and each value is an
10+
* array containing all items in the original array which generate that key.
11+
*
12+
* The provided callback fn will accept an item in the array and return a string key.
13+
*
14+
* The order of each value list should be the order the items appear in the array. Any order of
15+
* keys is acceptable.
16+
*
17+
* Please solve it without lodash's _.groupBy function.
18+
*/
19+
20+
/**
21+
* @param {Function} fn
22+
* @return {Object}
23+
*/
24+
Array.prototype.groupBy = function(fn) {
25+
return this.reduce((grouped, item) => {
26+
const key = fn(item);
27+
grouped[key] = grouped[key] || [];
28+
grouped[key].push(item);
29+
return grouped;
30+
}, {});
31+
};
32+
33+
/**
34+
* [1,2,3].groupBy(String) // {"1":[1],"2":[2],"3":[3]}
35+
*/

0 commit comments

Comments
 (0)