0

I ran across a paradox where sorting arrays works for number or number string values only. Here is the example:

const sortArr = (a, b) => a[1] - b[1];

const arr1 = [['two', '2'], ['one', '1'], ['three', '3']];
const arr2 = [['WA', 'Washington'], ['NC', 'North Carolina'], ['PA', 'Pennsylvania']];

let sortedArr1 = arr1.sort(sortArr);
let sortedArr2 = arr2.sort(sortArr);

console.log('sortedArr1', sortedArr1);  // returns sorted array
console.log('sortedArr2', sortedArr2);  // returns original array (not sorting)

Can someone help figure out the right ways how to sort arr2 by second values correctly? Thank you!

  • Are arrays sorted correctly in the output [here](https://i.stack.imgur.com/HUhzU.png)? If not, how should they be sorted instead? – Anderson Green Oct 29 '21 at 14:46

1 Answers1

0

Subtraction only works as the comparison function when you're comparing numbers. You need a comparison function that works with both numbers and strings.

function sortArr(a, b) {
    if (a == b) {
        return 0;
    else if (a < b) {
        return -1;
    } else {
        return 1;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612