Middle
// Implement the groupBy method that extends the standard array methods. // The method should return a grouped version of the array – an object, // where each key is the result of the function fn(arr[i]), // and each value is an array containing all elements of the original array with this key.
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; }, {}); };
// Example usage: const arr = [6.1, 4.2, 6.3]; const grouped = arr.groupBy(Math.floor); console.log(grouped); // Output: // { '4': [4.2], '6': [6.1, 6.3] }
This method extends the array prototype, 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 corresponding to those keys.