Skip to content

Instantly share code, notes, and snippets.

@leabs
Last active April 12, 2022 15:14
Show Gist options
  • Save leabs/0d972ef44433ba0e2b63d1c962f612c1 to your computer and use it in GitHub Desktop.
Save leabs/0d972ef44433ba0e2b63d1c962f612c1 to your computer and use it in GitHub Desktop.
Adding Javascript object arrays based on key-value pair (id)
// Add the number property of array1 and array2 where the id matches and declare as array3
let array1 = [{ id: 1, number: 3}, { id: 3, number: 4}, { id: 2, number: 4}]
let array2 = [{ id: 1, number: 3}, { id: 2, number: 5}, {id: 3,number: 3}]
let array3 = [];
for (let i = 0; i < array2.length; i++) {
for (let j = 0; j < array1.length; j++) {
if (array2[i].id === array1[j].id) {
array3.push({
id: array2[i].id,
number: array1[j].number + array2[i].number
})
}
}
}
console.log(array3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment