【问题标题】:Using reduce() to find the second largest element in the array使用 reduce() 查找数组中的第二大元素
【发布时间】:2021-06-08 20:55:24
【问题描述】:

是否可以使用 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]

}

【问题讨论】:

  • 请发布您尝试过的代码。
  • 是的,我认为这是可能的。你可以先分享你的努力吗?所以我们可以看到你可能在哪里挣扎?
  • 这能回答你的问题吗? Sorting Array with JavaScript reduce function
  • 请说明您是指排序函数,还是任何排序函数。我也同意,发布一些代码来展示你的尝试。

标签: javascript arrays reduce


【解决方案1】:

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

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

【讨论】:

  • 您可以考虑将问题标记为与stackoverflow.com/questions/50245957/… 重复吗?
  • 好吧,它不直接要求对数组进行排序,它要求获得第二大的值。另一个问题是关于不使用排序的排序。
  • 这个问题是通过链接问题中的排序方法来解决的。选择正确的项目是微不足道的
  • 是的,这是一种可能的解决方案,但您仍在排序,问题要求不要使用排序。我将其解释为不使用任何排序功能。
  • 感谢您的反馈。但是当我尝试数组 [12, 16, 1, 5] 时,它返回 0,我不知道为什么
猜你喜欢
  • 2012-12-25
  • 2016-03-19
  • 2015-01-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多