Hey there fellow Stack users,
Please excuse me if this question has already been asked or is too basic (I'm still new to Javascript).
Recently, I've been working on some w3c js challenges: Create a JavaScript function that can identify the second lowest and second greatest numbers in an array of stored numbers.
Here's my attempt:
var numbers = [3,8,5,6,5,7,1,9];
var outputArray = [];
function extractNumbers() {
var sortedNumbers = numbers.sort();
outputArray.push(sortedNumbers[1], numbers[numbers.length-2]);
return outputArray;
}
extractNumbers();
Now, here's the solution they provided:
function Second_Greatest_Lowest(arr) {
arr.sort(function(x,y) {
return x-y;
});
var unique = [arr[0]];
var result = [];
for(var j=1; j < arr.length; j++) {
if(arr[j-1] !== arr[j]) {
unique.push(arr[j]);
}
}
result.push(unique[1], unique[unique.length-2]);
return result.join(',');
}
alert(Second_Greatest_Lowest([1,2,3,4,5]));
I understand that the loop goes through until the input length, but I'm confused about the nested if statement inside the loop. It seems like a longer route to the solution.
Thanks!