Search code examples
javascriptarraysobjectgroupingjavascript-objects

Convert array of objects in an array of array of objects


I am retrieving data from a football (soccer) API. The specific data I need is an array of objects (306 objects). Every object has a property called matchday with a numeric value. I want to group all the objects that share the same property and store them in an array. What I need in the end is an array of array of objects.

Example array of objects:

[
  {id: 264796, matchday: 1, …},
  {id: 264797, matchday: 1, …},
  {id: 264798, matchday: 2, …},
  {id: 264800, matchday: 2, …},
]

What I want looks like this:

[
  [{id: 264796, matchday: 1, …},{id: 264797, matchday: 1, …}],
  [{id: 264798, matchday: 2, …},{id: 264800, matchday: 2, …}],
]

Solution

  • You can use .reduce() with Object.values() to get the desired output:

    const data = [
      {id: 264796, matchday: 1}, {id: 264797, matchday: 1},
      {id: 264798, matchday: 2}, {id: 264800, matchday: 2}
    ];
    
    const result = Object.values(
      data.reduce((r, c) => {
        r[c.matchday] = r[c.matchday] || [];
        r[c.matchday].push(c);
        return r;
      }, {})
    );
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }