Lilp
Lilp

Reputation: 971

Using reduce in Javascript to sum both empty and non empty arrays

I am trying to find a way to write a function that sums up all the elements within an array. I have been trying to implement this using JavaScripts reduce function. The problem I am having is that i want this function to work on both an empty array and an array with elements as separate scenarios. The following example passes the test case for an empty array but then not when the array has elements and vice versa.

function sum (numbers) {
  numbers = ['a', 'b', 'c'];
  return numbers.reduce(function (x, y, i) {
  return x + y + i; 
}), 0 };

I was looking at the signature of the reduce function and trying to implement this on the basis of that but something seems to be missing in my knowledge here.

function (previousValue, currentElement, currentIndex, array)

Upvotes: 0

Views: 1736

Answers (1)

Jamiec
Jamiec

Reputation: 136094

the following works with both an array of numbers, and an empty array (where the result will obviously be zero)

var sum = numbers.reduce(function(prev,curr){
    return curr + prev;
},0);

Below is a demo of both your scenarios

function sum(numbers){
  var x = numbers.reduce(function(prev,curr){
    return curr + prev;
  },0);
  return x;
}

alert(sum([1,2,3]));
alert(sum([]));

Upvotes: 5

Related Questions