0

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

SamM
  • 23
  • 1
  • 1
  • 4
  • 1
    Does this answer your question? [How to find the sum of an array of numbers](https://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Ivar Jun 19 '20 at 09:38
  • What is `sum += (ar)` supposed to do? `sum` is a number and `ar` an array. And why is `return sum` _in_ the loop? – Andreas Jun 19 '20 at 09:40
  • 1
    Two problems with your code: `sum += (ar);` tries to add the **array** `ar` to `sum`. You have to access the individual elements of the array instead (that's why you are using a loop). `return sum;` inside the loop will terminate the function (and therefore the loop) in the first iteration of the loop. Only return the sum *after* you have processed all array elements. – Felix Kling Jun 19 '20 at 09:40
  • 1
    `arr.reduce((a,v) => a + v ,0)` – bill.gates Jun 19 '20 at 09:45

1 Answers1

5

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]))
ABGR
  • 4,631
  • 4
  • 27
  • 49
  • 1
    why not omit parentese around the value of the array. it is superfluous and irritating, because it has no reason. – Nina Scholz Jun 19 '20 at 10:08