Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find smallest and biggest number of an array with reduce function in javascript

Tags:

javascript

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.

like image 957
cezarlamann Avatar asked Sep 28 '14 20:09

cezarlamann


3 Answers

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.

like image 69
RobG Avatar answered Oct 21 '22 08:10

RobG


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.

like image 27
sqykly Avatar answered Oct 21 '22 09:10

sqykly


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 }
like image 21
Rushikesh Bharad Avatar answered Oct 21 '22 07:10

Rushikesh Bharad