I'm making a data set for one of my components, current data is

    [ 
        {name  : "John" , id : "123"} ,
        {name  : "Josh" , id : "1234"},
        {name  : "Charlie" , id : "1234253"},
        {name  : "Charles" , id : "123345"}
    ]

want it to groupby like

    {
        C : [{name:"Charlie",id:"1234253"},{name:"Charles",id:"123345"}],
        J : [{name:"John",id:"123"},{name:"Josh",id:"1234"}]
    }

2 Answers

0
Drancis Lammer On Best Solutions

You want to examine all the objects in your input array, then push it into an array identified by the first letter of the name in your object.

var input = [{
    name: "John",
    id: "123"
  },
  {
    name: "Josh",
    id: "1234"
  },
  {
    name: "Charlie",
    id: "1234253"
  },
  {
    name: "Charles",
    id: "123345"
  }
];
var result = {};

input.forEach(x => !!result[x.name[0]] ? result[x.name[0]].push(x) : result[x.name[0]] = [x]);
console.log(result);

2
Hien Nguyen On

You can use reduce like this

var data =  [ 
        {name  : "John" , id : "123"} ,
        {name  : "Josh" , id : "1234"},
        {name  : "Charlie" , id : "1234253"},
        {name  : "Charles" , id : "123345"}
    ];
    
let result = data.reduce((r, e) => {
  
  let group = e.name[0];
 
  if(!r[group]) r[group] =  [e]
  
  else r[group].push(e);
  
  return r;
}, {})

console.log(result);