Middle
// Implement a groupBy method that extends the standard array methods. // The method should return a grouped version of the array — an object, // where the keys are the keys of the array from the results of calling the passed function fn(arr[i]), // and the values are arrays containing all the elements of the original array with this key. // code here // Example 1 const array1 = [ { id: 1 }, { id: 1 }, { id: 2 } ]; const fn = (item) => item.id; console.log(array1.groupBy(fn)); // { // 1: [{ id: 1 }, { id: 1 }], // 2: [{ id: 2 }] // } // Example 2 const array2 = [1, 2, 3]; console.log(array2.groupBy(String)); // { // "1": [1], // "2": [2], // "3": [3] // } // Example 3 const array3 = [1.3, 0.5, 1.4]; console.log(array3.groupBy(Math.round)); // { // 1: [0.5, 1.4], // 2: [1.3] // }
sobes.tech AI
Answer from AI
To extend the standard array methods in JavaScript, you can add a groupBy method to the Array prototype. This method takes a function fn that computes a key for each element and returns an object where the keys are the results of fn, and the values are arrays of elements with that key.
Example implementation:
Array.prototype.groupBy = function(fn) {
return this.reduce((acc, item) => {
const key = fn(item);
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(item);
return acc;
}, {});
};
Testing with examples:
const array1 = [
{ id: 1 },
{ id: 1 },
{ id: 2 }
];
const fn = (item) => item.id;
console.log(array1.groupBy(fn));
// {
// 1: [{ id: 1 }, { id: 1 }],
// 2: [{ id: 2 }]
// }
const array2 = [1, 2, 3];
console.log(array2.groupBy(String));
// {
// "1": [1],
// "2": [2],
// "3": [3]
// }
const array3 = [1.3, 0.5, 1.4];
console.log(array3.groupBy(Math.round));
// {
// 3: [1.3],
// 1: [0.5, 1.4]
// }
This method is useful for grouping data by any criterion.