Intern
// It is necessary to implement the groupBy method, extending the standard array methods. // The method should return a grouped version of the array - an object, // in which each key is the result of executing the passed function fn(arr[i]), // and each value is an array containing all 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 = [3.3, 0.5, 1.4]; console.log(array3.groupBy(Math.round)); // { // 3: [3.3], // 1: [0.5, 1.4] // }
sobes.tech AI
Answer from AI
javascript 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; }, {}); };
// Usage examples: const array1 = [ { id: 1 }, { id: 1 }, { id: 2 } ]; const fn = (item) => item.id; console.log(array1.groupBy(fn));
const array2 = [1, 2, 3]; console.log(array2.groupBy(String));
const array3 = [3.3, 0.5, 1.4]; console.log(array3.groupBy(Math.round));
The `groupBy` method is added to the array prototype and takes a function that returns a key for grouping. Then, using `reduce`, an object is formed where the keys are the results of the function, and the values are arrays of elements corresponding to those keys.