JS sort() sub array won't sort by alphabetic order

Hi,
why Sort() func would work for numeric but not for alphabetic in the follow example:
(the commented return is working, so nothing is wrong with the code itself)

var arr = [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [5, "Microphone"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]];
    
   arr=arr.sort(function(a,b){
     return a[1]-b[1];
     // return a[0]-b[0];
   });
console.log(arr)

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

You’re trying to subtract strings, which will give you NaN, not a very useful value. You can however use the < and > operators to sort strings. a < b will return true if a appears first in a dictionary than b (note that it’s a simplified explanation).

1 Like
  • thanks for the link and for the solution, it’s the 2nd time i fall for the >< sort thing.
  • But that’s why i like it here, not like StackOverflow, no one will vote-down u to hell for asking stupid questions:slight_smile: )

You have two options doing that with strings

First Option with <> :

var arr = [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [5, "Microphone"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]];
console.log(arr)
   arr=arr.sort(function(a,b){
     if (a[1]>b[1])
       return 1;
     else if (a[1]<b[1])
       return -1;
     else
       return 0;
     // return a[0]-b[0];
   });
console.log(arr)

Second Option with localCompare (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Sorting_non-ASCII_characters):

var arr = [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [5, "Microphone"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]];
console.log(arr)
   arr=arr.sort(function(a,b){
     return a[1].localeCompare(b[1]);
     // return a[0]-b[0];
   });
console.log(arr)