Middle
// Implement the groupBy method, extending 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 original array elements with that key.
sobes.tech AI
Answer from AI
It is possible to extend the array prototype by adding a groupBy method, which takes a function fn and returns an object where the keys are the result of calling fn on each element, and the values are arrays of elements with that key.
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); // { '4': [4.2], '6': [6.1, 6.3] }