JS阵列排序与正则表达式 [英] JS array sort with regex

查看:126
本文介绍了JS阵列排序与正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是根据使用正则表达式的JS对象的优先级对数组进行排序。这就是我所拥有的:

My objective is to sort an array based on the priority of JS object that uses regular expressions. Here's what I have:

JS对象定义:

var rx_CondoIndicator = new RegExp(/\bCONDO(MINIUM)?(?!S)/);

var rx_TownhouseIndicator = new RegExp(/\bTOWN\s*(HOUSE|HOME)(?!S)/);

var rx_TimeshareIndicator = new RegExp(/\bTIMESHARE(?!S)/);

定义的对象排序:

var so_UnitKeywordIndicator = {
    rx_CondoIndicator: 1,
    rx_TownhouseIndicator: 2,
    rx_TimeshareIndicator: 3
};

arrUnitNumber = ['TIMESHARE A-1', 'TOWNHOUSE 407', 'CONDO #13'] 

以下逻辑忽略排序对象优先级,并且不按所需顺序对数组进行排序,即CONDO#13,TOWNHOUSE 407,TIMESHARE A-1

The following logic ignores the sort object priority and does not sequence the array in the desired order which is "CONDO #13", "TOWNHOUSE 407", "TIMESHARE A-1"

arrUnitNumber.sort(function(x,y){
    return so_UnitKeywordIndicator[x] - so_UnitKeywordIndicator[y];
})

请注意,为简洁起见,只显示了一小部分JS排序对象。

Please note that only a fraction of the JS sort objects are shown for brevity.

如果这不是问题的最佳解决方案,我愿意接受任何JS新手的建议。

If this is not the best solution for the problem, I'm open to any suggestions being a novice at JS.

推荐答案

首先,将所有正则表达式放在一个数组中。列出它们的顺序将决定它们的排名,其中第一个元素是最高的。

First, put all of your regexes in an array. The order in which they are listed will determine their rank, where the first element is the highest.

var so_UnitKeywordIndicator = [rx_CondoIndicator, rx_TownhouseIndicator, rx_TimeshareIndicator];

现在这个函数将给出给定单位的等级。

Now this function will give the rank for a given unit.

function getSortRank(unit) {
    for (var i = 0; i < so_UnitKeywordIndicator.length; i++) {
        if (so_UnitKeywordIndicator[i].test(unit)) {
            return i;   
        }
    }
    return so_UnitKeywordIndicator.length;
}

最后,您可以使用此函数对像这样的单位数组进行排序:

Finally, you can then use this function to sort your array of units like this:

var sortedUnits = arrUnitNumber.sort(function(x, y) {
    return getSortRank(x) - getSortRank(y);
});

这篇关于JS阵列排序与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆