1

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
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Yusuf
  • 95
  • 7

2 Answers2

3

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);
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • 1
    Please don't answer a) poorly written questions and b) obvious duplicates. Even if we ignore the fact that the question doesn't actually ask the question your answer answers, it would be a duplicate of many others, such as [How to find the sum of an array of numbers](https://stackoverflow.com/q/1230233/215552) – Heretic Monkey Jun 02 '20 at 17:36
0

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)
Yevhen Kazmirchuk
  • 119
  • 1
  • 1
  • 6