Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • What is the difference between these sort functions (JavaScript)
    What is the difference between these sorts (implemented in JavaScript):
      var wArr = strArr.sort(function(a,b){
          return b.length-a.length;
      });
    
    And this sort:
      strArr = strArr.sort(function(a,b){
        if(a.length === b.length){
          return 0;
        } else {
          return b.length > a.length ? 1 : -1;
        }
      });
    
    I can use the top one to pass all test cases on the ThirdGreatest problem (Easy section). The bottom one passes most test cases but not all.
    DanielBank posted this question on 1/30/14 | javascript, sort, array
    Answers
  • +
  • 1
  • -
  • Hi Sveoryn, Thanks, you're right they are the same. I had inverted the a and b in the second sort function. I was actually using it like this:
      strArr = strArr.sort(function(a,b){
        if(a.length === b.length){
          return 0;
        } else {
          return a.length > b.length ? 1 : -1;
        }
      });
    
    Then I had to traverse my array from the last index to the first instead of the first to the last. That was causing test cases with multiples of the first and second largest numbers to fail. Thanks for your reply, Daniel
  • +
  • 0
  • -
  • Those sorts look they produce the same result to me... I just tried your second sort method and it returned that all test cases were correct. Which test cases did it say you got wrong? Just for reference, this is the full code I used when testing yours:
    function ThirdGreatest(strArr) { 
    
       strArr = strArr.sort(function(a,b){
        if(a.length === b.length){
          return 0;
        } else {
          return b.length > a.length ? 1 : -1;
        }
      });
          
      return strArr[2];
    }
    
    Log in to write an answer.