Categories
JavaScript Answers

How to Sort Alphanumeric Strings with JavaScript?

Spread the love

Sometimes, we want to sort alphanumeric strings with JavaScript.

In this article, we’ll look at how to sort alphanumeric strings with JavaScript.

String.prototype.localeCompare

We can use the string localeCompare method to compare strings so we can sort them.

For instance, we can write:

const arr = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12',
]
const sorted = arr.sort((a, b) => {
  return a.localeCompare(b, undefined, {
    numeric: true,
    sensitivity: 'base'
  })
})
console.log(sorted)

We call localeCompare to compare a and b naturally.

We set numeric to true to compare the numerical part of a and b .

sensitivity is set to 'base' to compare the case and the alphabet.

Therefore, sorted is:

["19asd", "123asd", "12345asd", "asd12", "asd123"]

Use Intl.Collator

Also, we can use the Intl.Collator constructor to create a collator instance which has the compare method to compare 2 strings.

For instance, we can write:

const arr = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12',
]
const collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: 'base'
});
const sorted = arr.sort((a, b) => {
  return collator.compare(a, b)
})
console.log(sorted)

The options are the same as localeCompare .

compare takes the 2 strings we want to compare.

Then sorted is the same result as before.

Conclusion

We can sort alphanumeric strings naturally with native JavaScript methods.

Leave a Reply

Your email address will not be published. Required fields are marked *