Find the min/max element of an Array in JavaScript

前端 未结 30 2054
無奈伤痛
無奈伤痛 2020-11-21 06:18

How can I easily obtain the min or max element of a JavaScript Array?

Example Psuedocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max()         


        
30条回答
  •  迷失自我
    2020-11-21 07:00

    For a concise, modern solution, one can perform a reduce operation over the array, keeping track of the current minimum and maximum values, so the array is only iterated over once (which is optimal). Destructuring assignment is used here for succinctness.

    let array = [100, 0, 50];
    let [min, max] = array.reduce(([prevMin,prevMax], curr)=>
       [Math.min(prevMin, curr), Math.max(prevMax, curr)], [Infinity, -Infinity]);
    console.log("Min:", min);
    console.log("Max:", max);

    To only find either the minimum or maximum, we can use perform a reduce operation in much the same way, but we only need to keep track of the previous optimal value. This method is better than using apply as it will not cause errors when the array is too large for the stack.

    const arr = [-1, 9, 3, -6, 35];
    
    //Only find minimum
    const min = arr.reduce((a,b)=>Math.min(a,b), Infinity);
    console.log("Min:", min);//-6
    
    //Only find maximum
    const max = arr.reduce((a,b)=>Math.max(a,b), -Infinity);
    console.log("Max:", max);//35

提交回复
热议问题