0

How can I turn this into a function that takes an array of any length and gives you the total?

var points = new Array(100);
for (var i = 0; i < 100; i++) {
    points[i] = i + 1; 
}

for(var i = 0; i < points.length; i++) {
    console.log(points[i]); 
}
4castle
  • 32,613
  • 11
  • 69
  • 106
Michael Melin
  • 13
  • 1
  • 4

5 Answers5

1

You can do get the sum using the for loop itself simply by using a variable

var points = new Array(100),
  sum = 0;

for (var i = 0; i < 100; i++) {
  points[i] = i + 1;
}

for (var i = 0; i < points.length; i++) {
  sum += points[i];
}

console.log(sum);

You can reduce these two operations using fill() and forEach() to generate the array and reduce() to get the sum

var points = new Array(10000); // create an array of size 10000
points.fill(1); // fill it with 1 which helps ti=o iterate using foreach

points.forEach(function(v, i) { // iterate the array, you can also use simple for loop here
  points[i] = v + i; // update the value
});

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

console.log(sum);

Using for loop and reduce()

var points = []; // initialize an array 

for (var i = 1; i <= 10000; i++) {
  points.push(i);
}

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

console.log(sum);

Also you can do the addition and array creation in single for loop

var points = [], // initialize an array 
  sum = 0;

for (var i = 1; i <= 10000; i++) {
  points.push(i); // pushing value to array
  sum += i; // summation 
}

console.log(sum, points);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 1
    Why should some arbitrary subset of a language be used just because you're newish? – rnevius May 24 '16 at 03:43
  • @rnevius because OP learns the basics of algorithms, ie: how to split tasks into subtasks and solve them separately step by step. This answer is not helpful for the OP. – zerkms May 24 '16 at 03:44
  • The `fill()` is kinda pointless. – shmosel May 24 '16 at 03:50
  • 2
    @zerkms, but how can you be sure that all future readers will be newish as is the OP today ? Also, someday OP will not be newish anymore, then he may find this answer helpful. – Kaiido May 24 '16 at 03:52
  • @Kaiido I'm not sure about anything, I try to not make any assumptions and not guess. What I know at the moment is: 1. OP is a newbie 2. They are solving basic learning exercise that teaches them how to use loops and basic operators. – zerkms May 24 '16 at 03:57
  • Same question here...why bother with extra loop even if it is `reduce`? – charlietfl May 24 '16 at 04:00
  • A `for` loop is pretty self-explanatory, especially for simple problems like this one, and most newbies can at least understand them when they see them even if they're a little confused about writing them from scratch. The `.reduce()` method is not at all self-explanatory: where do `a` and `b` come from? Where does the `return a+b` value *go*? How does that somehow add up the array? Those of us with experience understand, but this answer didn't explain or even link to some [`.reduce()` doco](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce). – nnnnnn May 24 '16 at 04:01
  • @charlietfl because OP cannot deal with loops properly, so `reduce` is definitely too much for them. – zerkms May 24 '16 at 04:01
  • @zerkms what I mean is why not do the summation in first loop. I fully follow the KISS principal about not using reduce – charlietfl May 24 '16 at 04:02
1
var result = 0;
for(var i = 0; i < points.length; i++) {
        result += points[i];
    }

Function that takes an array of any length and returns the sum:

function sumArray(arrayToSum){
    var result = 0;
    for(var i = 0; i < arrayToSum.length; i++) {
        result += points[i];
    }
    return result;
}
MikeT
  • 2,530
  • 25
  • 36
1

You could do it in two loops, but you might as well just do one loop that does both tasks.

var array = [],
    sum = 0;
for (var i = 1; i <= 10000; i++) {
    array[i-1] = i;
    sum += i;
}

If you want to generalize the task of finding the sum of an array, you can use a function like so:

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

For those who can understand it though, using reduce is a best answer:

function arraySum(array) {
    return array.reduce(function(a,b){return a+b}, 0);
}
4castle
  • 32,613
  • 11
  • 69
  • 106
  • "I'm not sure why the array is necessary here" --- because they are learning how to program, and it is their task. – zerkms May 24 '16 at 03:56
  • I've added an answer which shows how to make a function that does the same thing when the array already exists. – 4castle May 24 '16 at 04:07
0
function arraysum(arraylength) {
   var arraysum = 0;
   var array1 = new Array();
   for(i=1; i<=arraylength; i++) {
      array1.push(i);
   }
   for(i = 0; i< array1.length; i++) {
      arraysum += array1[i];
   }
   return arraysum;
}

Now when you call the function

arraysum(x)

pass the function some variable or integer for example 1, 15, or 10000.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27
WildCard
  • 527
  • 3
  • 8
-2

A very elegant and compact solution is to use reduce. It accumulates the array values to reduce it to a single value by applying each value and a start value to a given function, whose return value is used as the start value for the next iteration:

function sum (a, b) {
    return a + b;
}
console.log(points.reduce(sum, 0));

If you need to support older browser (e.g. IE 8) you can use a Polyfill.

If you need to create the list of numbers as well, you can create it with

var points = Array.apply(0, Array(10000))
    .map(function (current, index) { 
      return index + 1;  
  });

It creates an array of 10000 elements and assigns each element it's index + 1.

JSchirrmacher
  • 3,243
  • 2
  • 19
  • 27