Reputation: 1523
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.
Upvotes: 10
Views: 11100
Reputation: 1000
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.smallest < cur ? prev.smallest : cur;
prev.biggest = prev.biggest > cur ? prev.biggest : cur;
return prev;
}, initial);
console.log(result);
// Prints object as,
// { smallest: -1, biggest: 11 }
Upvotes: 3
Reputation: 10906
I know this is ancient but here is how to solve such issues using array reduce:
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
var minNumber = a.reduce(function(prev,cur) {
return prev < cur ? prev : cur;
}, +Infinity);
var maxNumber = a.reduce(function(prev,cur) {
return prev > cur ? prev : cur;
}, -Infinity);
Personally I'd just use Math.min/max
:
var a = [1,2,3,4,5,1,-1,6,7,8,9,10,2,11];
Math.min(...a) // will give -1
Math.max(...a) // will give 11
Upvotes: 2
Reputation: 147343
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.
Upvotes: 7
Reputation: 1586
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
.
Upvotes: 2