Javascript按上下文排序

时间:2017-11-15 10:55:15

标签: javascript sorting react-select

希望根据上下文对数组进行排序,其中包含以下示例数据

 ["1 Bob Smith", "12 Foo Bar", "112 Mary Jane", "122 Fizz Buzz"]

当我按12搜索时,它会返回

["12 Foo Bar", "112 Mary Jane", "122 Fizz Buzz"]

这似乎是我目前使用的库react-select的默认排序行为

我需要它返回的是以下

["12 Foo Bar", "122 Fizz Buzz", "112 Mary Jane"]

2 个答案:

答案 0 :(得分:1)

您可以使用所需搜索字符串的索引位置,然后先按字符串排序。

var array = ["1 Bob Smith", "12 Foo Bar", "112 Mary Jane", "122 Fizz Buzz" ,"12312 something"],
    value = '12',
    result = array.filter(a => a.includes(value));

result.sort(function (a, b) {
    return a.lastIndexOf(value) - b.lastIndexOf(value) || +(a > b) || -(a < b);
});

console.log(result);

使用搜索编号索引的方法,并使用带有选项的String#localeCompare进行排序,将其用作字符串。

var array = ["1 Bob Smith", "12 Foo Bar", "112 Mary Jane", "122 Fizz Buzz", "12312 something", "12101 bar"],
    value = '12',
    result = array.filter(a => a.includes(value));

result.sort(function (a, b) {
    function getPos(s) {
        var p = 0, h, r = [];

        s = s.match(/^\S+/)[0];
        while (p < s.length) {
            p = s.indexOf(value, p)
            r.push((p + 1) || 99999);
            if (p === -1) {
                break;
            }
            p += value.length;
        }
        return r.join(' ');
    }

    var aa = getPos(a), bb = getPos(b);

    return aa.localeCompare(bb, undefined, { numeric: true, sensitivity: 'base' }) || a.localeCompare(b);
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

你可能会喜欢;

&#13;
&#13;
var data   = ["1 Bob Smith", "12 Foo Bar", "112 Mary Jane", "122 Fizz Buzz"],
    result = data.sort((a,b) => a.match(/\d+\s+(.+)/)[1].localeCompare(b.match(/\d+\s+(.+)/)[1]))
                 .filter(s => s.includes("12"));
console.log(result);
&#13;
&#13;
&#13;