AI solution for JavaScript Coding Question on BFE.dev
177. Implement Object.groupBy()
To implement Object.groupBy()
, we can create a function that takes in an array of items and a grouping function as arguments.
The grouping function passed to Object.groupBy()
will determine how the items should be grouped. In the example provided, the grouping function extracts the kind
property from each item.
Here is the implementation of Object.groupBy()
:
Object.groupBy = function(arr, groupingFn) { return arr.reduce((acc, item) => { const key = groupingFn(item); if (!acc[key]) { acc[key] = []; } acc[key].push(item); return acc; }, {});}const items = [ { id: 1, kind: 'a', }, { id: 2, kind: 'b', }, { id: 3, kind: 'a', }]const groups = Object.groupBy(items, ({kind}) => kind);console.log(groups);
In this implementation, we use the reduce
method to iterate over the items array. For each item, we extract the key using the grouping function and check if there is already an array for that key in the accumulator. If not, we initialize an empty array for that key. We then push the item to the array for that key. Finally, we return the accumulator object containing all the groups.
When we run the code with the provided items, we get the expected result where items are grouped based on the kind
property.