I am trying to reduce an array to the sum of its even values. I have been checking on the document from MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
This says that if the initial value is provided then it won't skip the 0th index, in fact it will start from index 0. My problem is that the reduce is starting with index 1. Thus, my result is incorrect. I am sure I am reading the document incorrectly or misunderstanding it. This is the note I am referring to - "Note: If initialValue is not provided, reduce() will execute the callback function starting at index 1, skipping the first index. If initialValue is provided, it will start at index 0."
Here is my code.
var array = [1,2,3,4,6,100];
var initialValue = 0;
var value = array.reduce(function(accumulator, currentValue, currentIndex, array, initialValue) {
//console.log(accumulator);
if( currentValue % 2 === 0) {
accumulator += currentValue;
//return accumulator;
}
return accumulator;
});
console.log(value);
Obviously, I am seeing the result 113 and not 112. I guess, it is because accumulator already has a value 1. Thus, it is adding 1 initially.