Reputation: 95
I've been trying to make a calculator in JavaScript.
My issue is I don't know how to find the sum of 2 arrays (the first number (33) is saved to an array called num1 ) (the second number (99) is saved to an array called num2 ) example(33+99 = ?)
I wrote the below statement but the total returns in a concatenated format ex(1,3,5,3) which is not my intended solution
const calculate = (n1,n2) => {
let result =""
if (n1.length > 0 ){
result = n1 + n2
}
return result
}
v.push(calculate(num1, num2))
document.getElementById("answer").innerHTML = v
Upvotes: 1
Views: 99
Reputation: 129
The example to use only one reduce:
let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
array1.concat(array2).reduce((a,v) => a + v,0)
Or even like that:
let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
[...array1, ...array2].reduce((a,v) => a + v,0)
Upvotes: 0
Reputation: 14914
Use .reduce()
let array1 = [1,2,3,4,5];
let array2 = [1,2,3,4,5];
let result = array1.reduce((a,v) => a + v,0) + array2.reduce((a,v) => a + v,0);
console.log(result);
Upvotes: 3