Javascript - Second Highest Number

Find the Second Largest Number in an Array:

I have been doing 7 days of JavaScript challenge on Hacker Rank and one of the day 3 challenges was:

You are given N numbers. Store them in an array and find the second largest number.

The sample input array is [2, 3, 6, 6, 5] so I was thinking about duplicates going into solving this. Duplicates prevented me from just sorting and then taking the second to last number by index.

To get a unique array I used Array.prototype.filter() which creates a new array with all the elements that pass a test that you can write.

function processData(myArray) {
	var unique = myArray.filter(function(element, position){
		return myArray.indexOf(element) === position;
	});
}

The myArray.indexOf(element) is the index of the first occurence of the element in the array. The return statement evaluates to either true or false and if it's true that element gets pushed into the array. In the sample array, when the first 6 is iterated over it's index is 2 (myArray.indexOf(element)) and its position is 2 so this returns true and it gets added to the unique array. The second 6's position is 3 but the index (myArray.indexOf(element)) is still 2 so it is not added to the array unique.

So now I had solved the duplicate problem I decided to sort these in order so I added:

var sorted = unique.sort(function(a,b) {
    return a - b;
});

A basic unique.sort() wouldn't work with numbers because the numbers are converted into strings and for example '50' would come before '6.' Therefore, a compare function is supplied (function(a,b) {return a-b;}) which there is more detail about on MDN.

Then I had a unqiue array (with no duplicates) in ascending, numerical order and I can just grab the second do last value with:

var result = sorted[sorted.length - 2];

To put it all together:

function processData(myArray) {
  var unique = myArray.filter(function(item, pos) {
    return myArray.indexOf(item) === pos;
  });
  var sorted = unique.sort(function(a, b) {
    return a - b;
  });
  var result = sorted[sorted.length - 2]
  return result;
}