Reputation: 1
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
}
]
Upvotes: 0
Views: 213
Reputation: 39
This can help you
var results = array.reduce(function(results, org) {
(results[org.id] = results[org.id] || []).push(org);
return results;
}, {})
I took it of: Group by Object ID's in Javascript
Upvotes: 1