mercredi 27 janvier 2016

Understanding get second lowest and second highest value in array

Good day fellow Stack-ers,

I must ask your pardon if this question has been asked before or if it seems elementary (I am only a Javascript novice).

I have been doing w3c js challenges lately: Write a JavaScript function which will take an array of numbers stored and find the second lowest and second greatest numbers.

Here is my answer:

var array = [3,8,5,6,5,7,1,9];
var outputArray = [];

function arrayTrim() {
  var sortedArray = array.sort();
  outputArray.push(sortedArray[1],array[array.length-2]);
  return outputArray;
}

arrayTrim();

and here is they answer they have provided:

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(',');  

}  

alert(Second_Greatest_Lowest([1,2,3,4,5])); 

I know that the for loop runs through until the length of the input, but I don't understand the if statement nested within the for loop. It seems like a long way around to the solution.

Thank you!

Aucun commentaire:

Enregistrer un commentaire