根据数组元素中的子字符串对 Javascript 数组进行排序

Sort Javascript array based on a substring in the array element

var arr = ["This is three", "This is four", "This is one", "This is two", ...];

如果我有一个如上所示的数组,我需要根据字符串中的子字符串值对数组进行排序 - 即一、二、三.., 解决问题的最佳方法是什么?

我的最终结果应该是

var sortedArr = ["This is one", "This is two", "This is three", "This is four", ...];

此解决方案使用包含数字的数组,并在字符串中查找数字单词和 returns 排序索引。

对于更大的数组,我建议使用sorting with map

var sortedArr = ["This is four", "This is two", "This is one", "This is three"];

sortedArr.sort(function (a, b) {
    function getNumber(s) {
        var index = -1;
        ['one', 'two', 'three', 'four'].some(function (c, i) {
            if (~s.indexOf(c)) {
                index = i;
                return true;
            }
        });
        return index;
    }
    return getNumber(a) - getNumber(b);
});

document.write('<pre>' + JSON.stringify(sortedArr, 0, 4) + '</pre>');

编辑:

~ is a bitwise not operator. It is perfect for use with indexOf(), because indexOf returns if found the index 0 ... n and if not -1:

value  ~value   boolean
 -1  =>   0  =>  false
  0  =>  -1  =>  true
  1  =>  -2  =>  true
  2  =>  -3  =>  true
  and so on