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 [
You could use the ids as properties of an object
let 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'},
];
let grouped = groupArray(api_array);
console.log(grouped);
console.log(grouped[1]);
function groupArray(myArray) {
let grouped = {};
for (let i = 0; i < myArray.length; i++) {
let row = myArray[i];
let group = grouped[row.id];
if (!group) {
group = [];
grouped[row.id] = group;
}
group.push(row);
}
return grouped;
}