Last active
April 12, 2022 15:14
-
-
Save leabs/0d972ef44433ba0e2b63d1c962f612c1 to your computer and use it in GitHub Desktop.
Adding Javascript object arrays based on key-value pair (id)
This file contains 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
// 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