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;