1

I'm trying to console log the sum of all the numbers from 1 to 10 (as see in my console.log and me calling the functions) but I'm just stumped.

In my first function I made it so the array would fill up and print out everything in between whatever i set for start and end. I have no idea how to rework the sum function to make the console.log show me 55 (the sum of all the numbers between 1 and 10)

    a = [];

var range = function(start, end) {
  for (j=start;j<=end;j++) {
  a.push(j);

  }
  return a;
}

var sum = function(array) {
  var array = a;
}



console.log(sum(range(1, 10)));

Like I said, it's the sum function that's giving me trouble. I'm stumped how to make it work with in the context of this little program.

  • Possible duplicate of [How to find the sum of an array of numbers](http://stackoverflow.com/questions/1230233/how-to-find-the-sum-of-an-array-of-numbers) – Grant Macdonald Apr 20 '17 at 00:18
  • why is the only statement in `sum` clobbering the incoming array argument? - hint ... `array.reduce((a, b) => a + b)` – Jaromanda X Apr 20 '17 at 00:18

3 Answers3

1

Like I said, it's the sum function that's giving me trouble.

you'll need to add all the numbers within the array then return the result:

a = [];

var range = function(start, end) {
  for (j=start;j<=end;j++) {
  a.push(j);

  }
  return a;
}

var sum = function(array) {
    var result = 0;
    for(var i = 0; i < array.length; i++) result += array[i];
    return result;
}

console.log(sum(range(1, 10)));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You should be able to use a reducer function

var a = [];
    
var range = function(start, end) {
  for (j=start;j<=end;j++) {
  a.push(j);

  }
  return a;
}

var sum = function(array) {
  return array.reduce(function(a, b) {
    return a + b;
  })
}

alert(sum(range(1,10)))

See here Array.reduce MDN

aaronw
  • 136
  • 2
  • 9
-1

You can use map to run a function on all the items in the array like:

var a = [];
    
var range = function(start, end) {
  for (j=start;j<=end;j++) {
  a.push(j);

  }
  return a;
}

var sum = function(a) {
  var accum = 0;
  a.map(function(item) {
    accum += item;
  });
  return accum;
}

console.log(sum(range(1,10)))
Chase
  • 3,009
  • 3
  • 17
  • 23