Skip to content
Advertisement

Java script create new array grouped by object properties [closed]

I am learning Java script and trying to merge an Array of objects depending on the specific properties of that object.

For example I have the following array which contains objects of properties a,b,c,pet and age. I want to create a new array with pet and age grouped if the properties a,b,c are same for 2 objects. If any of the properties in a,b,c are not matched i want to add them as a new object to my output array.

JavaScript

Output array grouped by properties a,b,c. the first element of my output array contains the combined values of objects 0,1 in input array as they have same properties of a,b,c. remaining are added as seperate values as they differ in one the properties.

JavaScript

Towards the end I want a array with all elements grouped by property a,b,c. Is there a efficient way to this? I tried brute forcing with for loops but it didnt work.

TIA.

Advertisement

Answer

1) You can easily achieve the result using Map and for..of

JavaScript
JavaScript

2) You can also achieve the samer result using Object.values and reduce

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement