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)
[<>]snippet editor.