I need to group common objects to single with count,how to group the object based on the id in the object and how to add extra key with count in result.
var a =[
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
]
output =
[
{"name":"test","id":101,"price":100,"qty":2},
{"name":"test3","id":103,"price":10,"qty":1},
{"name":"test2","id":102,"price":12,"qty":1},
]
CodePudding user response:
Try the following (certainly not the fastest but works ;):
let myarray = [
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
];
let groupedArray = myarray.reduce((acc, cur) => {
let foundIndex = acc.findIndex(a => a.id == cur.id);
if (foundIndex != -1){
acc[foundIndex].qty = 1
} else {
cur.qty = 1; acc.push(cur)
}
return acc;
}, []);
// groupedArray contains the grouped objects
CodePudding user response:
const a =[
{"name":"test","id":101,"price":100},
{"name":"test","id":101,"price":100},
{"name":"test3","id":103,"price":10},
{"name":"test2","id":102,"price":12},
];
const output = a.reduce((acc, nv, i, arr) => {
const item = acc.find(e => e.id === nv.id);
if(item) return acc;
acc.push({ ...nv, count: arr.filter(e => e.id === nv.id)?.length });
return acc;
}, []);