JavaScript array reduce start from index -
this problem has been bugging me while , can't seem find answer in web.
is possible use array reduce method starting index?
simple example
var studentgrades = ["john doe", "some school", 6, 7, 8, 7, 9, 9];
if need loop on integers in studentgrades, can simple loop
for(var = 2; < studentgrades.length; i++) { // stuff here ... }
but let's need average grade sum of integers divided integers count. if array contained integers, there no problem using reduce.
var onlyintegersarr = [5,2,3,4]; var averagegrade = onlyintegersarr.reduce(function(a,b){ return + b; }) / onlyintegersarr.length;
however if know whatever reasons need skip first 2 array elements , start index array[2].
so example apply reduce studentgrades, starting index studentgrades[2].
is possible reduce?
thank solutions, slice approach, prefer not using new method in case.
e.g.
var average = studentgrades.reduce(function(a,b,i){ return >= 2 ? a+b : 0; }) / (studentgrades.length - 2);
reduce's 3rd argument index, here fiddle
var averagegrade = onlyintegersarr.reduce(function (a, b, c) { if (c >= 2) { return + b; } else { return 0; } });
if array has more non-numeric items after second index check fiddle
var studentgrades = ["john doe", "some school", 6, 7, 8, 7, 9, 9, "some school"]; var averagegrade = studentgrades.reduce(function (a, b, c) { if (c >= 2 && !isnan(b)) { return + b; } else if (c >= 2) { return + 0; } else { return 0; } }) alert(averagegrade);
Comments
Post a Comment