I spent hours trying to debug a particular code, at the very end i noticed something i don't understand with arr reduce function. Take the below code example
var arr = [{
start: 1,
value: 4
}, {
start: 2,
value: 5
}, {
start: 3,
value: 1
}, {
start: 4,
value: 41
}, {
start: 5,
value: 14
}, {
start: 6,
value: 3
}];
const getMinValue = function(a, b) {
return (a.value < b.value) ? a.start : b.start;
}
console.log('The min value ', arr.reduce(getMinValue));
The console above returns 6.However, from, the array , its noticeable that the value is minimum at start:3
. Rewriting the code to below however,
var arr = [{
start: 1,
value: 4
}, {
start: 2,
value: 5
}, {
start: 3,
value: 1
}, {
start: 4,
value: 41
}, {
start: 5,
value: 14
}, {
start: 6,
value: 3
}];
const getMinValue = function(a, b) {
return (a.value < b.value) ? a : b;
}
console.log('The min value ', arr.reduce(getMinValue));
returns object {start: 3, value: 1}
which is exactly correct. Hence
console.log('The min value ', arr.reduce(getMinValue).start);
is correct. Why does the first one differ pls ? Why does it return 6 ? . Is there something i am mistaking about reduce or my getMin function ? Any help would be appreciated.