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 [
//Create a javascript array of objects containing key value pairs id, post
var api_array = [
{id: 1, postcode: '10'},
{id: 1, postcode: '11'},
{id: 2, postcode: '20'},
{id: 2, postcode: '21'},
{id: 2, postcode: '22'},
{id: 3, postcode: '30'}
];
//result is a javascript array containing the groups grouped by id.
let result = [];
//javascript array has a method foreach that enumerates keyvalue pairs.
api_array.forEach(
r => {
//if an array index by the value of id is not found, instantiate it.
if( !result[r.id] ){
//result gets a new index of the value at id.
result[r.id] = [];
}
//push that whole object from api_array into that list
result[r.id].push(r);
}
);
console.log(result[1]);
console.log(result[2]);
console.log(result[3]);
Prints:
[ { id: 1, postcode: '10' }, { id: 1, postcode: '11' } ]
[ { id: 2, postcode: '20' },
{ id: 2, postcode: '21' },
{ id: 2, postcode: '22' } ]
[ { id: 3, postcode: '30' } ]