Search code examples
javascriptarrayssuminteger

Simple Array Sum using javascript (single integer)


Been finding the this sum difficult to solve:

Question: Given an array of integers, find the sum of its elements.

For example, if the array ar = [1,2.3],1+2+3=6 so return 6.

Function Description

Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.

I have tried:

function simpleArraySum(ar) {
    var sum = 0;
    for (var i = 0; i <ar.length; i++) {
    sum += (ar);
    return sum;
    }
}

Output is: 01,2,3,4,10,11

It should be 31.

Help please


Solution

  • There are two problems in your code. You need to change

    sum += (ar); to sum += (ar[i]);

    so as to sum the element at that index and not the ar itself. Also return should be outside the loop and should actually be the return of the function. Otherwise, for..loop will just return after the first execution.

    function simpleArraySum(ar) {
      var sum = 0;
      for (var i = 0; i < ar.length; i++) {
        if(typeof ar[i] == `number`) sum += ar[i];
      }
      return sum;
    }
    
    console.log(simpleArraySum([1, 2, 3, 4]))