Apologies if this question seems a bit silly. I’m in the middle of a project and there’s one line I can’t make sense of right now
function minSum(arr) {
return arr.reduce((acc,curr,index) => acc += curr * arr[arr.length - index - 1])
//.reduce((acc,curr,index) => acc += curr * arr[arr.length - index - 1], 0)
}
console.log(minSum([5,4,2,3]))
this returns 36 (5x3 + 4x2 + 2x4 + 4x5) however when the commented line is used instead, with 0 as initial value, 46 is returned instead. Why is this? Where is 0 thrown in the calculation?
The first time that the callback is run there is no “return value of the previous calculation”. If supplied, an initial value may be used in its place. Otherwise array element 0 is used as the initial value and iteration starts from the next element (index 1 instead of index 0).
Thank you for your response, I really appreciate it.
I understand that when no initial value is given, the first element is selected and the calculation is simply as I mentioned above. However, what would the calculation be if an initial value of 0 is specified? I can’t see how it would increase the final value by 10.