Skip to content

Instantly share code, notes, and snippets.

@beall49
Last active January 13, 2023 16:17
Show Gist options
  • Save beall49/9353932fdb28469a654f1e1221598c5d to your computer and use it in GitHub Desktop.
Save beall49/9353932fdb28469a654f1e1221598c5d to your computer and use it in GitHub Desktop.
const makeSet = (list) => {
return list.reduce((items, item) => {
const id = item.id;
const value = item.value
const found = items.find(i => i.id === id);
if (!found) {
items.push(item);
} else {
found.value += value;
}
return items;
}, []);
};
const list = [
{ id: 1, value: 2 },
{ id: 1, value: 6 },
{ id: 3, value: 1 },
{ id: 3, value: 3 },
{ id: 5, value: 3 },
{ id: 5, value: 10 },
]
const set = makeSet(list);
console.log(set);
/* [ { id: 1, value: 8 }, { id: 3, value: 4 }, { id: 5, value: 13 } ] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment