I have an array with objects and each object has a unique ID. I need to separate these objects according to their ID's and create new arrays containing objects with only the same ID.
This is what I have so far..
let fullArray = [{
name: 'John',
id: 1
}, {
name: 'Lucy',
id: 1
}, {
name: 'Tyler',
id: 2
}];
function separateObjectsInArray(fullArray) {
let newArr = [];
fullArray.map((each) => {
newArr.push(each.id);
});
let uniqueIdArr = [...new Set(newArr)];
fullArray.map((eachObj) => {
uniqueArr.map((uniqueId) => {
if (eachObj.id === uniqueId) {
//CREATE NEW ARRAYS WITH MATCHING ID'S
}
})
})
}
separateObjectsInArray(fullArray);
As you can see I first mapped out the array of objects then created an array with the ids, then took out any duplicates (uniqueIdArr) Afterwards I am mapping the fullArray again and comparing the IDs of each objects to the ID's uniqueIdArr. I'm stuck on how to tell it to create an array for each ID and push matching objects.
let finalArray1 = [{
name: 'John',
id: 1
}, {
name: 'Lucy',
id: 1
}];
let finalArray2 = [{
name: 'Tyler',
id: 2
}];
OR even one array with the arrays is fine too!
let finalArray = [[{name: 'Tyler', id: 2 }], [{ name: 'John', id: 1},{
name: 'Lucy', id: 1 }]];