How to sort an array of alphanumeric strings in JavaScript

Last updated on Jun 13, 2021 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


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.