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 [
{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'},
];
I am trying to achieve this result:
result [
group_one [
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
group_two [
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
group_three [
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
group_four [
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
]
I have actually managed to achieve it but i think its crazy and am sure there is a better implementation here is what i have done:
const createAddresses = (address) => {
let group_one= [],
group_two = [],
group_three = [],
group_four = [],
group = [];
debugger;
for(let i=0; i < address.length; i++) {
switch (address[i].id) {
case 1:
group_one.push(address[i]);
break;
case 2:
group_two.push(address[i]);
break;
case 3:
group_three.push(address[i]);
break;
case 4:
group_four.push(address[i]);
break;
default:
return address;
}
}
console.log('GROUP', group);
return group.push(group_one, group_two, group_three, group_four);
}
I really dont like this implementation and have tried this:
const obj = address.reduce((acc, cur) => ({...acc, [cur.id]: cur}), {});
and what the above does is the same as my insane for loop function but it only adds last element for each group like so:
result [
0 [
{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
1 [
{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
2 [
{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
3 [`enter code here`
{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},
]
]
but like i have mentioned i need all the elements in side each group any advice please.
See Question&Answers more detail:
os