Ecrire son propre GroupBy avec la méthode Reduce

Cet extrait de code montre une manière d’appeler la méthode reduce() pour effectuer un groupBy sur un tableau d’objets.

function groupBy(objectArray, property) {
    return objectArray.reduce((acc, obj) => {
      var key = obj[property];
      if (!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj);
      return acc;
    }, {});
}

Exemple

var people = [
  { name: "Alice", age: 21 },
  { name: "Max", age: 20 },
  { name: "Jane", age: 20 }
];

console.log(groupBy(people,"age"))

Sortie

{ '20': [ { name: 'Max', age: 20 }, { name: 'Jane', age: 20 } ],
  '21': [ { name: 'Alice', age: 21 } ] }

Leave a Reply

Your email address will not be published. Required fields are marked *