Search code examples
javascriptarraysjsonjavascript-objects

sort the objects in array that has same value to one object inside the same array


I am making Fetch request that return array of objects as follow:

[
   {"id":11,"name":"test1","day":"MON","level":2},
   {"id":13,"name":"test2","day":"TUE","level":3},
   {"id":14,"name":"test1","day":"WED","level":4},
   {"id":15,"name":"test2","day":"FRI","level":5}
]

So, inside this array I have four objects each two have the same name, so I want the result to be like this:

 {
           "test1" : [
                       {"id":11,"name":"test1","day":"MON","level":2}, 
                       {"id":14,"name":"test1","day":"WED","level":4}
                    ],
           "test2" :[
                      {"id":13,"name":"test2","day":"TUE","level":3}, 
                      {"id":15,"name":"test2","day":"FRI","level":5}
                    ]
  }

Solution

  • you can use a reduce function

    const arr = [
       {"id":11,"name":"test1","day":"MON","level":2},
       {"id":13,"name":"test2","day":"TUE","level":3},
       {"id":14,"name":"test1","day":"WED","level":4},
       {"id":15,"name":"test2","day":"FRI","level":5}
    ];
    
    const result = arr.reduce((acc, cur) => {
        acc[cur.name] = acc[cur.name] || [];
      acc[cur.name].push(cur);
      return acc;
    }, {})
    
    console.log(result);
    console.log(Object.values(result).flat());