I have this array of objects that goes like this
let data = [
{
"id": 1,
"name": "Sam",
"father": true,
"group": "orange"
},
{
"id": 2,
"name": "Alex",
"father": true,
"group": "red"
},
{
"id": 3,
"name": "Rock",
"father": true,
"group": "blue"
},
{
"id": 4,
"name": "Liam",
"father": false,
"group": "red"
},
{
"id": 5,
"name": "Noah",
"father": false,
"group": "red"
},
{
"id": 6,
"name": "Oliver",
"father": false,
"group": "orange"
},
{
"id": 7,
"name": "Sara",
"father": false,
"group": "blue"
},
{
"id": 8,
"name": "Max",
"father": false,
"group": "red",
}
];
And I want to sort it so every father has his children as a key called "member" which is an array of objects inside the father object. the children has to be the same color of his father's. so for example the output should be something like this :
{
"id": 1,
"name": "Sam",
"father": true,
"group": "orange"
"member":[
{
"id": 6,
"name": "Oliver",
"father": false,
"group": "orange"
}];
{
"id": 2,
"name": "Alex",
"father": true,
"group": "red"
"member":[
{
"id": 4,
"name": "Liam",
"father": false,
"group": "red"
},
{
"id": 5,
"name": "Noah",
"father": false,
"group": "red"
},
{
"id": 8,
"name": "Max",
"father": false,
"group": "red",
}
];
and so on .. I made it works but I used nested loops , this is my code :
function sorting(data) {
//loop in all objects and find me all fathers
data.forEach(fatherObjects => {
if (fatherObjects.father) {
var member = [];
//loop in all children objects and find me all children that has the same father color
data.forEach(childrenObjects => {
if (!childrenObjects.father && childrenObjects.group === fatherObjects.group) {
//add children objects to 'member' array
member.push(childrenObjects)
}
});
//add 'member array vlaues to the member key inside father objects'
fatherObjects["member"] = member;
console.log(fatherObjects);
}
});
}
sorting(data);
This is working and all however this runs so slow because of the two nested loops How can I replace it with something more efficient and not so complex to understand.
groupis it the first time an item is found which becomes the father?