How to sort an array of strings and numbers in JavaScript

#javascript #array

Last updated on Dec 14, 2020 by Suraj Sharma



In this tutorial, you will learn how you can sort alphanumeric values in a JavaScript array.


const array = ["1", "A1", "D2", 4, "11A", 2];

//Expected ["1", 2, 4, "11A", "A1", "D2"]

The sort() method sorts an array by converting the elements into strings, then comparing their sequences of UTF-16 code units values.


Therefore, the array.sort() method behaves weirdly with an array containing strings and numbers.


Example


const array = ["1", "A1", "D2", 4, "11A", 2];

array.sort();

// returns ["1", "11A", 2, 4, "A1", "D2"]


The best way to sort the alphanumeric array is to use the String.localeCompare() method inside the comparator function


Example


const array = ["1", "A1", "D2", 4, "11A", 2];

const comparator = (a, b) => {
  return a.toString().localeCompare(b.toString(), 'en', { numeric: true })
};

array.sort(comparator);

// returns ["1", 2, 4, "11A", "A1", "D2"] as expected

The localeCompare() method returns 1 if a reference string comes before, -1 it comes after or 0 if the reference string is the same as the given string.



Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.