1

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?

Community
  • 1
  • 1
user1526912
  • 15,818
  • 14
  • 57
  • 92

1 Answers1

1

Assuming that for each priorityId, there is only one type.

function group(arr) {
    return arr.reduce(function(acc, o) {
        if(acc[o.priorityId])                                       // if we already encountered this priorityId before...
            acc[o.priorityId].colors.push(o.color);                 // then just add this object's color to the array colors of this priorityId objects
        else                                                        // otherwise (if we haven't encounter it yet)...
            acc[o.priorityId] = {type: o.type, colors: [o.color]};  // then create an object for it that has its type set to this object's type and its colors array containing (initially) this object's color
        return acc;
    }, {});
}


var data = [
    { 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"  }
];

console.log(group(data));
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73