Seeking explanation to sorting Multi-Dimensional array by column

Hi, in relation to Inventory Update algorithm challenge, I was stuck on sorting for a long time with this:

arr1 = arr1.sort(function(a,b) {
             
             return a[1] - b[1];
             
             });

I did some research on the forum and came across Gaben14’s code and when I implemented it, I was able to get it working

arr1 = arr1.sort(function(a,b) {
             
             
             if (a[1] < b[1]) return -1;
             if (a[1] > b[1]) return 1;
             return 0;
             });

just wondering why my function is not able to sort “Half-Eaten Apple”, “Hair Pin” and “Microphone”? as when I used my code it will always sort like: “Hair Pin” "Microphone and “Half-Eaten Apple” Thank you in advance.

The sort function uses the return value of the callback function to determine what to do with the sort - does it need to swap that pair or leave it as is?

You are subtracting,

  return a[1] - b[1];

It understands what to do if it returns a 0, or greater than 0 or less than 0.

But you seem to be comparing strings. What does it mean to subtract a string from string? JavaScript just returns NaN.

The second option doesn’t subtract the strings but compares them. That, it can do. And it returns either -1, 1, or 0 - depending on what is needed.

  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;