简体   繁体   中英

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

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

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)

You could group the values and sort the array of arrays and get the second array.

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

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