Questions : Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.
Not sure how this solution works :
function Second_Greatest_Lowest(arr_num) {
arr_num.sort(function(x, y) {
return x - y;
});
var uniqa = [arr_num[0]];
var result = [];
for (var j = 1; j < arr_num.length; j++) {
if (arr_num[j - 1] !== arr_num[j]) {
uniqa.push(arr_num[j]);
}
}
result.push(uniqa[1], uniqa[uniqa.length - 2]);
return result.join(',');
}
I think I understand what is happening in the loop, but I'm not sure why that is necessary when later uniqa[1] is pushed into the result array. Aren't they performing the same action?
array[1]andarray[array.length - 2].uniqaif the previous number is different from the current one. I guess to make sureuniqa[1]is not the same asuniqa[0](and likewise for the last two numbers in the array)