0

I know the question has been answered, I have no problem with the solution other than it doesn't work for all the cases. I'm required to return the second largest value in an array, this is my solution for now in Javascript(node.js):

function getSecondLargest(nums) {
// Complete the function
const unique = (value, index, self) => {
    return self.indexOf(value) === index
}
let nums_new = nums.filter(unique);
//console.log(nums_new)      //New array has no duplicate values
nums_new.sort();
//console.log(nums_new)      //New array is sorted in ascended order
nums_new.reverse();
//console.log(nums_new)      //New array is reversed to get it in descending order
return nums_new[1];          //The second largest value is returned
}

The question is from 10 days of JS on hackerrank, the first case:

5
2 3 6 6 5

Produces the correct output 5.

But when I try the second input case:

10
1 2 3 4 5 6 7 8 9 10

the expected output is nine but I get 8. I used log statements to see what's going on, the second console.log statement shows this output:

[ 1, 10, 2, 3, 4, 5, 6, 7, 8, 9 ]

Why is the first value in the array not included in the sort statement? The third console.log statement shows this output:

[ 9, 8, 7, 6, 5, 4, 3, 2, 10, 1 ]

So the function returns 8 as an output instead of 9, why is that? why did the sort function behave this way?

  • 1
    Because JS `sort` works on strings, not numbers. See https://www.w3schools.com/js/js_array_sort.asp – fredrik Feb 20 '20 at 11:22
  • 1
    `nums_new.sort((a, b) => a-b)` fixes the algorithm. `Array#sort` documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort – Ben Aston Feb 20 '20 at 11:30

0 Answers0