I'm currently learning Java script and attempting to merge an Array of objects based on certain properties of those objects.
For instance, I have the following array which consists of objects with properties a, b, c, pet, and age. I aim to create a new array where pet and age are grouped if the properties a, b, c match for 2 objects. If any of the properties in a, b, c do not match, I want to include them as a new object in my output array.
myArray = [
{
a: 'animal',
b: 'white',
c: true,
pet: 'dog1',
age: 1
},
{
a: 'animal',
b: 'white',
c: true,
pet: 'dog2',
age: 2
},
{
a: 'animal2',
b: 'white',
c: true,
pet: 'cat1',
age: 5
},
{
a: 'animal2',
b: 'black',
c: false,
pet: 'cat2',
age: 1
}
]
The output array should be grouped by properties a, b, c. The first element of my output array will contain the combined values of objects 0 and 1 from the input array since they share the same properties of a, b, c. Any differing objects will be added separately.
outputArray = [
{
a: 'animal',
b: 'white',
c: true,
pets: [{pet:'dog1,age:1},{pet:dog2,age:2}]
},
{
a: 'animal2',
b: 'white',
c: true,
pets: [{pet: 'cat1', age:5}]
},
{
a: 'animal2',
b: 'black',
c: false,
pets:[{pet: 'cat2', age: 1}]
}
]
In the end, I would like an array with all elements grouped by property a, b, c. Is there a more efficient way to achieve this? I attempted using for loops but it was not successful.
Thank you in advance.