javascript - Understanding get second lowest and second highest value in array -


good day fellow stack-ers,

i must ask pardon if question has been asked before or if seems elementary (i javascript novice).

i have been doing w3c js challenges lately: write javascript function take array of numbers stored , find second lowest , second greatest numbers.

here 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 answer 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 loop runs through until length of input, but don't understand if statement nested within loop. seems long way around solution.

thank you!

your answer not perform correct input such f.e. [3,8,5,6,5,7,1,1,9]. proposed solution returns 1 second lowest number here – whereas should 3.

the solution suggested site takes account – if inside loop for, checks if current number same previous one. if that’s case, gets ignored. way, every number occur once, , in turn allows blindly pick second element out of sorted array , have second lowest number.

it seems long way around solution

you took short cut, not handle edge cases correctly ;-)


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -