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;
3
  • 2
    Looks like you're just grouping by end and concatenating ('summing') name. Plenty of duplicates Commented Sep 26, 2022 at 21:03
  • 4
    "name": "foo and bar" is a bad idea, it looks like it would be a horrible value to deal with. Commented Sep 26, 2022 at 21:05
  • Maybe one of those can answer your question: this, this, this, this Commented Sep 26, 2022 at 21:15

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.