如何在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
    nin 回复

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

    arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
    
    arr.sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
    console.log(arr);