JavaScript array reduce start from index

JanisSt picture JanisSt · Jan 27, 2016 · Viewed 12.3k times · Source

This problem has been bugging me for a while now and I can't seem to find an answer in web.

Is it possible to use Array reduce method starting from a certain index?

simple example

var studentGrades = ["John Doe", "Some School", 6, 7, 8, 7, 9, 9];

If I need to loop over only integers in studentGrades, I can do that with a simple for loop

for(var i = 2; i < studentGrades.length; i++) {
  // do stuff here ...
}

But let's say I would need get an average grade which is sum of all integers divided by integers count. If Array contained only integers, then there would be no problem using reduce.

var onlyIntegersArr = [5,2,3,4];
var averageGrade = onlyIntegersArr.reduce(function(a,b){
  return a + b;
}) / onlyIntegersArr.length;

However if I know that for whatever reasons I need to skip the first two Array elements and start from index Array[2].

So for example I would apply reduce to studentGrades, but only starting from index studentGrades[2].

Is that possible with reduce?

Thank you for solutions, I like slice approach, but I prefer not using a new method in this case.

e.g.

var average = studentGrades.reduce(function(a,b,i){
  return i >= 2 ? a+b : 0;
}) / (studentGrades.length - 2);

Answer

Jaromanda X picture Jaromanda X · Jan 27, 2016

If you know for a fact that you want to skip the first n elements, you can use Array#slice

Using ES2015 Arrow Function

var sum = array.slice(n).reduce((a, b) => a + b);

var studentGrades = ["John Doe", "Some School", 6, 7, 8, 7, 9, 9];
var sum = studentGrades.slice(2).reduce((a, b) => a + b);

document.body.innerHTML = 'SUM is = ' + sum;

In ES5, the same code can be written using anonymous function.

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

var studentGrades = ["John Doe", "Some School", 6, 7, 8, 7, 9, 9];
var sum = studentGrades.slice(2).reduce(function(a, b) {
    return a + b;
});

document.body.innerHTML = 'SUM is = ' + sum;

for the case you mentioned, of only adding up numeric values, regardless of where in the array they are - you could do something like

var sum = array.reduce(function(result, v) {
    return result + (parseFloat(v) || 0);
}, 0);

var studentGrades = ["John Doe", "Some School", 6, 7, 8, 7, 9, 9];
var sum = studentGrades.reduce(function(result, v) {
    return result + (parseFloat(v) || 0);
}, 0);

document.body.innerHTML = 'SUM is = ' + sum;