I have 2 different arrays in javascript, they have always the same length and I need to count one element + another element from another array with same index
let arr1 = [1, 2, 3];
let arr2 = [8, 9, 2];
Expected Output
1 + 8 = 9
2 + 9 = 11
3 + 2 = 5
let result = [9, 11, 5]
What would be the easiest and the most elegant way to do it? I tried for loop and map as well but I didn´t find working solution
can achieve this with just 1 map
let arr1 = [1, 2, 3];
let arr2 = [8, 9, 2];
const sums = arr1.map((e,index) => e+arr2[index])
console.log(sums)
or a simple for loop
let arr1 = [1, 2, 3];
let arr2 = [8, 9, 2];
const sums = []
for(let i=0; i<arr1.length; i++){
sums.push(arr1[i]+arr2[i])
}
console.log(sums)
or with a forEach
let arr1 = [1, 2, 3];
let arr2 = [8, 9, 2];
const sums = []
arr1.forEach((e,index) => {
sums.push(e+arr2[index])
})
console.log(sums)
or with reduce
let arr1 = [1, 2, 3];
let arr2 = [8, 9, 2];
const sums = arr1.reduce((acc,curr,index) => {
acc.push(curr+arr2[index])
return acc
},[])
console.log(sums)