Last active
January 13, 2023 16:17
-
-
Save beall49/9353932fdb28469a654f1e1221598c5d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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