1

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

3
  • 1
    Please add your attempt so we can fix it. Commented Jul 28, 2020 at 6:54
  • Please visit the help center, take the tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output using the [<>] snippet editor. Commented Jul 28, 2020 at 6:56
  • 2
    What if the array was [5,5,5,5] ? Commented Jul 28, 2020 at 6:58

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

but will this work for say an array const arr = [1, 2, 5, 5,7,7,7,6] ?
would return [6]
oh yes ....sorry it works fine , mybad .... question here and the requirement is confusing
2

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)

3 Comments

You should point out that there could be performance implications if the array is large enough: we are sorting also parts of the array we are not interested into. But I agree: this is the simpler and cleaner approach.
@A.Chiesa I have added that, thanks for the feedback
@A.Chiesa I have fixed the code thanks for pointing that out
1

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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.