-4

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"}]
    }
Hassan Raza
  • 173
  • 1
  • 1
  • 6

2 Answers2

2

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);
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
0

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);
Ferenc
  • 527
  • 3
  • 6