I am trying to loop through a array ob objects and group the items of the array into new arrays that have matching id:
API example:
api_array [
Try to acheive like this:
var api_array = [
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
];
const result = api_array.reduce((acc, item) => {
acc[`group_${item.id}`] = (acc[`group_${item.id}`] || []);
acc[`group_${item.id}`].push(item);
return acc;
}, {});
console.log(result);
Note: The result will have keys group_1
, group_2
... instead group_one
, group_two
...
If you strictly need that, then make an array for key and values to convert 1 as one.