I am trying to group data using Array.prototype.reduce()
I am grouping by priorityId and my data is as follows:
{ priorityId: 100, type: train color: black }
{ priorityId: 50, type: car, color: orange }
{ priorityId: 25, type: bike, color: yellow }
{ priorityId: 50, type: car, color: grey }
{ priorityId: 25 type: bike, color: white }
{ priorityId: 25, type: bike, color: green }
I followed the solution posted here and the grouping works perfectly fine: What is the most efficient method to groupby on a javascript array of objects?
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
My grouping now looks like the following
groupedItems:
25:
{ priorityId: 25 type: bike, color: yellow }
{ priorityId: 25, type: bike, color: white }
{ priorityId: 25, type: bike, color: green}
50:
{ priorityId: 50, type: car, color: orange }
{ priorityId: 50, type: car, color: grey }
100:
{ priorityId: 100, type: train, color: black }
I ultimately wish to group my data like this:
25: {
type: bike
colors: [yellow, white, green]
},
50:{
type: car
colors:[ orange, grey]
},
100:{
type: train
colors: [black]
}
The problem I am experiencing is I cannot iterate over my grouped items from my reduced grouped items . The items appears as an array, however 0 length therefore I cannot map to get my desired final grouping.
How can I further extract my reduced grouped items to achieve the final results?