【发布时间】:2021-11-09 14:16:13
【问题描述】:
考虑以下数组:
['state1035', 'dm5', 'state123', 'county247', 'county2']
根据数字输出对该数组进行排序应该是:
['county2' ,'dm5', 'state123', 'county247', 'state1035']
【问题讨论】:
标签: javascript sorting arraylist
考虑以下数组:
['state1035', 'dm5', 'state123', 'county247', 'county2']
根据数字输出对该数组进行排序应该是:
['county2' ,'dm5', 'state123', 'county247', 'state1035']
【问题讨论】:
标签: javascript sorting arraylist
假设字符串将包含数字,最后您可以使用 match 提取数字并对其进行排序:
let arr = ['state1035', 'dm5', 'state123', 'county247', 'county2'];
console.log(arr.sort((a,b) => a.match(/\d+$/).pop() - b.match(/\d+$/).pop()));
比较函数中使用的匹配方法将返回给定字符串中匹配的子字符串数组。正则表达式\d+ 将匹配末尾的数字,我们将根据这些数字进行排序。
【讨论】:
仅针对字符串中的数字使用regular expression 到match,然后根据这些数字使用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);
【讨论】: