Find smallest and largest number of array with reduction function in javascript

Just a matter of curiosity. With the reduce function, we could easily find the smallest and largest number inside the array separately. Similar:

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 this doesn'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.

+5
source share
4 answers

In the following:

 a.reduce(function(prev,cur,index,array){ smallest = prev < cur ? prev : cur; biggest = prev > cur ? prev : cur; }); 

the function provided to reduce does not have a return statement, therefore returns undefined. Therefore, after the first iteration, prev is set to undefined.

If any expression in the abstract relational comparison algorithm is undefined, the expression returns undefined (see step 3.c), which evaluates to false. Thus, starting from the second iteration, both the minimum and the largest are set to cur, and at the end they are both set to the last value in the array.

+4
source

Two problems.

First, the reduce lambda parameter has no return value. If you are not going to return something, reduce just forEach with a lot of parameters that mean nothing.

Secondly, for each element, you compare cur with prev instead of comparing cur with biggest and smallest .

+2
source

I know this is ancient, but here's how to solve such problems using array reduction:

 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); 
0
source

When using reduction, you need to return something inside the reduction, otherwise reduce the values โ€‹โ€‹of the 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 } 
0
source

Source: https://habr.com/ru/post/1203568/


All Articles