Does anyone know of a way to group an array of objects by two property.
I have array like this:
[
{
index: 4,
name: "car",
price: [10,20,30]
},
{
index: 4,
name: "car",
price: [40,50,60]
},
{
index: 3,
name: "bike",
price: [40,50,60]
},
{
index: 2,
name: "scooter",
price: [10,20,60]
},
{
index: 2,
name: "scooter",
price: [70]
},
]
so I would like that the output looks like this
[
{
index: 4,
name: car,
price: [40,50,60,10,20,30]
},
{
index: 3,
name: bike,
price: [40,50,60]
},
{
index: 2,
name: scooter,
price: [10,20,60, 70]
}
]
Objects that have the same name and index, connect, i.e. connect the price array.
3
Answers
You can do this like this if you are using javascript.
Try this and let me know whether it works or not.
You could take an emoty object for grouing along with an array for the grouping keys and build a string with values, like
of
for a key which reflects
index
andname
.Then push all prices to the according group. At the end take only the values as result.
I wrote a quick solution that converts your data into an ‘associative array’.
It assumes that the index/name pair will always be unique, i.e. index 4 will always be ‘car’.