简体   繁体   English

在 javascript 中查找具有重复项的数组中的第二大元素

[英]Find second largest elements in array with duplicates in javascript

Am having array to find second largest elements including repeated value pls find below example.我有数组来查找第二大元素,包括重复值,请在下面找到示例。

const arr= [1,2,5,5,6] 

expected result should be预期结果应该是

[5,5]

I tried with map and math.max but i stuck up on logical issue.kindly help me我尝试使用 map 和 math.max 但我坚持逻辑问题。请帮助我

Below snippet could help you下面的片段可以帮助你

 const arr = [1, 2, 5, 5, 6] const max = Math.max(...arr) const newArr = arr.filter(element => element.== max) const newMax = Math.max(...newArr) const secondLargest = arr.filter(element => element === newMax) console.log(secondLargest)

Here is a simpler approach, However it may not be the best approach in terms of performance for large data这是一种更简单的方法,但是就大数据的性能而言,它可能不是最佳方法

 const ar= [1,2,5,5,6] secmax = Math.max(...ar.filter((n,i) => Math.max(...ar).=n )) res = ar.filter(n =>n == secmax) console.log(res)

Using a Set to extract unique values shortens the code quite a bit使用 Set 提取唯一值可以大大缩短代码

var arr = [1,5,2,5,4,8];
var uniqueValues = [...new Set(arr)].sort((a, b) => b-a);
var secondHighest = uniqueValues[1]; // 0 is max, 1 is second highest, etc.
var result = arr.filter(x => x === secondHighest);

Please keep in mind that there should be some due diligence in accessing the results (what happens if the code is fed with empty arrays, or arrays with a single repeated value? There are many cases not covered here)请记住,在访问结果时应该进行一些尽职调查(如果代码输入为空 arrays 或 arrays 具有单个重复值,会发生什么情况?这里没有介绍很多情况)

You could group the values and sort the array of arrays and get the second array.您可以对值进行分组并对 arrays 的数组进行排序并获得第二个数组。

 const array = [1, 2, 5, 5, 6], result = Object.values(array.reduce((r, v) => (r[v] = [...(r[v] || []), v], r), {})).sort(([a], [b]) => b - a) [1]; console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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