I am having difficulty grouping an array with its sub-array. Here is the original array I am working with:
var people = [
{
name: "Bob",
age: "20",
car: {
colour: "Blue",
size: "Big",
rpm: "380"
}
},
{
name: "Mary",
age: "21",
car: {
colour: "Orange",
size: "Small",
rpm: "20"
}
},
{
name: "Janet",
age: "22",
car: {
colour: "Blue",
size: "Big",
rpm: "380"
}
}
];
My goal is to group the data by the color of the car object in this specific format:
var cars = [
{
colour: "Blue",
size: "Big",
rpm: "380",
people: [{ name: "Bob", age: "20" }, { name: "Janet", age: "22" }]
},
{
colour: "Orange",
size: "Small",
rpm: "20",
people: [{ name: "Mary", age: "21" }]
}
];
As a newcomer to JavaScript, any assistance or suggestions you can offer would be greatly appreciated. I am open to using external libraries if necessary.
EDIT In response to @ths, I managed to extract the car object into the main array successfully using the following code:
resultArray = [];
people.forEach(function(people) {
let carObj = people.car;
console.log("TCL: carObj", carObj)
carObj["people"] = people;
resultArray.push(carObj);
});
However, I encountered difficulties when trying to merge the arrays based on different car types.