I have an array of objects. All objects have the same properties. I'm trying to find a way to create new arrays for each of the common id's. This is my array: `
var array =
[
{
id: "BG",
qty: 100
},
{
id: "BG",
qty: 35
},
{
id: "JP",
qty: 75
},
{
id: "JP",
qty: 50
}
];
`
I wan it to create arrays based on the id property. Based on the above array, I'm expecting 2 arrays for BG and JP.
I tried this but it creates an array with just the 2 id's
const uniqueId = [...new Set(array.map(array => array.id))];
What I want my result to be is:
[{
id: "BG",
qty: 100
},
{
id: "BG",
qty: 35
}]
[{
id: "JP",
qty: 75
},
{
id: "JP",
qty: 50
}
]
array.reduce()is your friendarray.reduce((obj, cur) => (obj[cur.id] = [...(obj[cur.id] || []), cur], obj), {})?groupBywould do what you want here._.groupBy(array, 'id')returns{ BG: [{ id: 'BG', qty: 100 }, { id: 'BG', qty: 35 }], JP: [{ id: 'JP', qty: 75 }, { id: 'JP', qty: 50 }] }