# 如何在Javascript中使用正则表达式对数组进行排序？ [重复]

``````arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"]
``````

As you can see, each element in the array has `#n` associated with it where `n` is any number between `0-9`. Now based on the `n`, I want to sort by array in ascending order such that the final output looks like this

``````[ '#0abc', '#0pol kol', '#1loa', '#2egf', '#2ko pol' ]
``````

``````rankWordMap = {}
finalArr = []
arr.forEach(function(entry) {
rank = entry.charAt(1)
if(rankWordMap[rank]) {
rankWordMap[rank].push(entry);
}
else {
rankWordMap[rank] = [entry];
}

})

for (var key in rankWordMap) {
if (rankWordMap.hasOwnProperty(key)) {
finalArr.push(...rankWordMap[key])
}
}

console.log(finalArr)
``````

• 木叶 回复

您可以匹配前几位，并使用此值进行排序。

``````var
getValue = string => string.match(/\d+/),
array = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];

array.sort((a, b) => getValue(a) - getValue(b));

console.log(array);``````
• nin 回复

无需正则表达式，只需根据每个条目中第二个字符的整数值进行排序：

``````arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];

arr.sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
console.log(arr);``````