如何仅根据 javascript 中的数字对字母数字数组进行排序?

How to sort an alphanumeric array just based on number in javascript?

考虑以下数组:

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

根据数字输出对这个数组进行排序应该是:

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

假设字符串将数字放在一起,最后您可以使用匹配来提取数字并对其进行排序:

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

比较函数中使用的匹配方法将 return 给定字符串中的匹配子字符串数组。正则表达式 \d+ 将匹配末尾的数字,我们将根据这些数字进行排序。

使用 regular expression to match against only the numbers in the string, and then sort 基于这些数字的字符串。

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);