Sobes.tech
Middle+

// 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));

sobes.tech AI

Answer from AI

The groupBy method groups array elements by a key computed by a function passed as an argument. As a result, it produces an object where the keys are the values returned by the function, and the values are arrays of elements corresponding to those keys.

Example implementation of groupBy for an array:

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:
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]
// }