简体   繁体   中英

Using reduce() to find the second largest element in the array

Is it possible to use reduce to find the second largest element in an array? Without using sort methods. Something like this:

Obs: The code below is for finding the largest value. I need to find the second largest value and would like to use reduce(). Without using the sort methods


array1 =  [12, 16, 1, 5]
array2 = [8, 4, 5, 6];

function largestElement(array){

    largestE = array.reduce((acc,currentValue) => currentValue > acc ? currentValue : acc )

    return largestE
}


console.log(largestElement(array1))
console.log(largestElement(array2))

WITHOUT DOING THIS:


 function secondLargest(array){
    
    array.sort((a,b) => a-b)
    return array[array.length-2]

}

Yes there are several ways you can do this. Here is one solution:

 const array1 = [5, 5, 1, 1, 2, 3, 4]; const array2 = [12,16,1,5]; const reducer = (accumulator, currentValue, idx, a) => { let larger = a.filter(n=>n>currentValue) // Fetch larger values than n.filter((n,i,a) => a.indexOf(n) === i); // Get Unique values if(larger.length === 1){ // if there is only one unique value larger than n, n is your answer. return accumulator = currentValue; } else { return accumulator = accumulator; // else preserve the accumulator value } } console.log(array1.reduce(reducer)); console.log(array2.reduce(reducer));

I think that the simpler the better, I will just create two variables and compare each element of the array First make two variables outside the loop inside the loop just ask if current number is bigger than larger

  1. if its bigger then assign the value to largest and make the secondLargest with the values of largest 2)if it is not larger than largest but it is smaller than secondLargest than pass that numbe to the secondLargest, please see the code below
    function FindSecondLargest() {
    largest = 0
        secondLargest =0
        for (let i =0 i<array.length, i++)
        {
          if(array[i] >largest)
          {
            secondLargest = largest 
            largest=array[i]
          }else if(array[i] <secondLargest){
            secondLargest=array[i] 
          }
          
        }
      return secondLargest;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM