Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

109
Views
Sort array of arrays with string values [JavaScript]

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!

7 months ago · Juan Pablo Isaza
1 answers
Answer question

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;
    }
}
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs