微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 reduce() 查找数组中的第二大元素

如何解决使用 reduce() 查找数组中的第二大元素

是否可以使用reduce来查找数组中的第二大元素?不使用排序方法。像这样:

Obs:下面的代码用于寻找最大值。我需要找到第二大值并想使用reduce()。不使用排序方法


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))

如果不这样做:


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

}

解决方法

是的,有几种方法可以做到这一点。这是一种解决方案:

const array1 = [5,5,1,2,3,4];
const array2 = [12,16,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));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。