Just a matter of curiosity. With the reduce function, we could easily find the smallest and the biggest number inside an array separately. Just like that:
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
a.reduce(function(prev,cur,index,array){
return prev > cur ? prev : cur;
}); // returns 11
a.reduce(function(prev,cur,index,array){
return prev < cur ? prev : cur;
}); // returns -1
Given that, why this don't work?
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
var smallest = 0;
var biggest = 0;
a.reduce(function(prev,cur,index,array){
smallest = prev < cur ? prev : cur;
biggest = prev > cur ? prev : cur;
});
console.log([smallest, biggest]); // prints [11,11]
Tested on repl.it.
In the following:
a.reduce(function(prev,cur,index,array){
smallest = prev < cur ? prev : cur;
biggest = prev > cur ? prev : cur;
});
the function supplied to reduce has no return statement so it returns undefined. So after the first iteration, prev is set to undefined.
If either expression in the abstract relational comparison algorithm is undefined, the expression returns undefined (see step 3.c), which evaluates to false. So from the second iteration onward, both smallest and biggest are set to cur and at the end they're both set to the last value in the array.
Two problems.
First, the lambda parameter to reduce
has no return value. If you aren't going to return something, reduce
is just forEach
with more parameters that don't mean anything.
Second, at each element, you compare cur
to prev
instead of comparing cur
to biggest
and smallest
.
While using reduce, you need to return something inside reduce, otherwise reduce forgets previous values.
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
var initial = {
smallest: a[0],
biggest: a[0]
};
var result = a.reduce((prev, cur) => {
prev.smallest = prev < cur ? prev : cur;
prev.biggest = prev > cur ? prev : cur;
return { smallest, biggest};
}, initial);
console.log(result);
// Prints object as,
// { smallest: -1, biggest: 11 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With