Home > Back-end >  How to sort an alphanumeric array just based on number in javascript?
How to sort an alphanumeric array just based on number in javascript?

Time:09-17

consider the following array:

['state1035', 'dm5', 'state123', 'county247', 'county2']

sorting this array on basis of number output should be:

['county2' ,'dm5', 'state123', 'county247', 'state1035']

CodePudding user response:

Assuming the strings will have numbers together and at the end you can use match to extract the number and sort it:

let arr = ['state1035', 'dm5', 'state123', 'county247', 'county2'];
console.log(arr.sort((a,b) => a.match(/\d $/).pop() - b.match(/\d $/).pop()));

The match method used within the compare function will return the array of matched sub-strings from the given string. The regex \d will match with numbers at the end and we are sorting based on these numbers.

CodePudding user response:

Use a regular expression to match against only the numbers in the string, and then sort the strings based on those numbers.

const data = ['state1035', 'dm5', 'bob0Bob', 'state123', 'county247', 'county2'];

const regex = /\d /;

const result = data.sort((a, b) => {
  return a.match(regex) - b.match(regex);
});

console.log(result);

  • Related