0

I've got an array of objects:

let events = [
  {"name": "blah", "end": "8"},
  {"name": "foo", "end": "9"},
  {"name": "bar", "end": "9"}
]

that I'd like to turn into a combined array, like so:

let events = [
  {"name": "blah", "end": "8"},
  {"name": "foo and bar", "end": "9"}
]

I know I can do this with a for loop and a new temporary holding array, but is there any JS Array function magic that could do this in one line? Something with reduce and/or map or something? My currently working loop code:

let combined = [];
for (let hour of events) {
  let alreadyExists = combined.find(x => x.end === hour.end);
  if (alreadyExists) {
    alreadyExists.name = alreadyExists.name + ' and ' + hour.name;
  } else {
    combined.push(hour);
  }
}
events = combined;
xd1936
  • 1,038
  • 2
  • 9
  • 27
  • 2
    Looks like you're just grouping by `end` and concatenating ('summing') `name`. Plenty of duplicates – pilchard Sep 26 '22 at 21:03
  • 4
    `"name": "foo and bar"` is a bad idea, it looks like it would be a horrible value to deal with. – zer00ne Sep 26 '22 at 21:05
  • Maybe one of those can answer your question: [this](https://stackoverflow.com/questions/73451895/how-to-merge-2-arrays-with-nested-objects-into-1-array-without-duplicates/73452122#73452122), [this](https://stackoverflow.com/questions/73449152/mapping-arrays-into-object-with-values-as-an-array/73449812#73449812), [this](https://stackoverflow.com/questions/54376660/how-to-merge-object-values-of-two-objects/73423418#73423418), [this](https://stackoverflow.com/questions/73419719/merge-nested-objects-in-javascript-and-append-matching-properties-in-array/73420289#73420289) – Rodrigo Rodrigues Sep 26 '22 at 21:15

0 Answers0