Question

This is a follow-up question of this one, although both are unrelated in term of operation


Starting with this kind of structure:

[ [{ field: "field1", term: "val1"},
   { field: "field2", term: "val2"}
  ],
  [{ field: "field3", term: "val3"},
   { field: "field3", term: "val4"},
   { field: "field4", term: "val5"}
  ],
  [{ field: "field3", term: "val6"},
   { field: "field2", term: "val7"},
   { field: "field3", term: "val8"},
   { field: "field1", term: "val9"},
   { field: "field2", term: "val10"}
  ]
]

I need to iterate through each child arrays, and for each object inside, aggregate the values of the key term into an array when the key field is the same; And by the same occasion wrap all values of key term in an array, for simplicity later. End result would be like so:

[ [{ field: "field1", term: ["val1"]},
   { field: "field2", term: ["val2"]}
  ],
  [{ field: "field3", term: ["val3", "val4"},
   { field: "field4", term: ["val5"]}
  ],
  [{ field: "field3", term: ["val6", "val8"]},
   { field: "field2", term: ["val7", "val10"]},
   { field: "field1", term: ["val9"]}
  ]
]

I've tried playing with _.reduce for each objects, got relatively close but never quite there. Not mastering this pattern at all, I am not convinced reduce is the way to go either

Any ideas or pointers? Been trying to wrap this one for 2 days ... :S

Thanks

Was it helpful?

Solution

Well, you can create for each array a new object that's got "field" values as keys, and "term" arrays as values. Then you can transform that back into objects in your original form.

var newArray = array.map(function( subArray ) {
  var obj = subArray.reduce(function(m, o) {
    if (o.field in m)
      m[o.field].push(o.term);
    else
      m[o.field] = [o.term];
    return m;
  }, {});

  return Object.keys(obj).map(function(field) {
    return { field: field, term: obj[field] };
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top