Sort alphanumerical string in JavaScript

Let's assume that we are working with the following array:

javascript
let array = ['5 4 B', '1 2 C', '3 1 C', '3 4 A', '3 1 A'];

Sort in ascending order

If we want to sort it in ascending order we can use localeCompare():

javascript
let sorted = array.sort((a, b) => a.localeCompare(b));

console.log(sorted);
// ["1 2 C", "3 1 A", "3 1 C", "3 4 A", "5 4 B"]

Last character as the most important

If we want to sort the array considering the last character as the most important one:

javascript
// Defining array
let array = ['5 4 B', '1 2 C', '3 1 C', '3 4 A', '3 1 A'];

// Setting last char in the first position ["B 5 4", "C 1 2", "C 3 1", "A 3 4", "A 3 1"]
let lastCharFirst = array.map(string => `${string[string.length - 1]} ${string.slice(0, string.length - 2)}`);

// Sorting in ascending order ["A 3 1", "A 3 4", "B 5 4", "C 1 2", "C 3 1"]
let sorted = lastCharFirst.sort((a, b) => a.localeCompare(b));

// Setting char in the last position again
let lastCharLast = sorted.map(string => `${string.slice(1)} ${string[0]}`);

console.log(lastCharLast);
// [" 3 1 A", " 3 4 A", " 5 4 B", " 1 2 C", " 3 1 C"]

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.