user9896359
user9896359

Reputation:

Calculate the sum of array of numbers

I'm new at javascript and am trying to finish up a test. So far I've done ok, but I can't seem to get right the three last things: - it should return the sum with one number array - it should return zero if all elements are zero - it should return the sum when passed array of numbers

const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];

function sumNumbers(arr){
  if (arr === undefined || arr.length == 0) {
    return 0;
  }
  array.reduce(function(a, b){
    return a + b;
}, 0);
}

Upvotes: 1

Views: 72

Answers (2)

Mamun
Mamun

Reputation: 68933

You should return the result of reduce, there is no array named array, should be arr:

return arr.reduce(function(a, b){

const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];

function sumNumbers(arr){
  if (arr === undefined || arr.length == 0) {
    return 0;
  }
  return arr.reduce(function(a, b){
    return a + b;
}, 0);
}
console.log(sumNumbers(numbers));

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386816

You need to return the result of return and take the same variable array.

function sumNumbers(array) {
  if (array === undefined || array.length == 0) {
    return 0;
  }
  return array.reduce(function(a, b) {
    return a + b;
  }, 0);
}

const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];

console.log(sumNumbers(numbers));

A shorter approach uses a default array and return just the result of reduce.

function sumNumbers(array) {
    return (array || []).reduce(function(a, b) {
        return a + b;
    }, 0);
}

const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];

console.log(sumNumbers(numbers));

Upvotes: 0

Related Questions