Sobes.tech
Middle+

Implement the Array.prototype.groupBy method, which returns a structured version of an array of objects, where each key is the result of the passed function call, and the value is an array of elements corresponding to this key.

sobes.tech AI

Answer from AI

The groupBy method groups array elements by a key computed by a provided function. It returns an object where the keys are the results of the function, and the values are arrays of elements corresponding to those keys.

Example implementation of Array.prototype.groupBy:

if (!Array.prototype.groupBy) {
  Array.prototype.groupBy = function(callback) {
    return this.reduce((acc, item, index, array) => {
      const key = callback(item, index, array);
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(item);
      return acc;
    }, {});
  };
}

// Example usage:
const data = [
  { category: 'fruit', name: 'apple' },
  { category: 'vegetable', name: 'carrot' },
  { category: 'fruit', name: 'banana' }
];

const grouped = data.groupBy(item => item.category);
console.log(grouped);
/*
{
  fruit: [ { category: 'fruit', name: 'apple' }, { category: 'fruit', name: 'banana' } ],
  vegetable: [ { category: 'vegetable', name: 'carrot' } ]
}
*/

This method is useful for structuring data based on specific attributes.

Implement the Array.prototype.groupBy method, which… - sobes.tech