且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据字符串中的数字对数组进行排序?

更新时间:2022-03-15 22:55:06

使用sortreduce获取结果时,可以使用正则表达式获取数字:

You can use regular expression to get the numbers when using sort and reduce to get the result:

var array = [ "22x0", "3x9", "2x1" ];

var reS = /^\d+/,                          // regexp for getting all digits at the start of the string
    reE = /\d+$/;                          // regexp for getting all digits at the end of the string
var result = array.sort(function(a, b) {   // First: sort the array
    a = reE.exec(a);                       // get the last number from the string a
    b = reE.exec(b);                       // get the last number from the string b
    return b - a;                          // sort in a descending order
}).reduce(function(res, str, i) {          // Then: accumulate the result array 
    var gap = reE.exec(array[i - 1]) - reE.exec(str); // calculate the gap between this string str and the last string array[i - 1] (gap = N_of_last_string - N_of_this_string)
    if(gap > 0)                            // if there is a gap
        while(--gap) res.push(0);          // then fill it with 0s
    res.push(+reS.exec(str));              // push this string number
    return res;
}, []);

console.log("Sorted array:", array);       // array is now sorted
console.log("Result:", result);            // result contain the numbers

在最新的ECMAScript版本中,您可以使用以下箭头功能很快完成此操作:

In recent ECMAScript versions you can do it shortly using arrow functions like this:

let array = [ "22x0", "3x9", "2x1" ];

let reS = /^\d+/,                       
    reE = /\d+$/;                      
let result = array.sort((a, b) => reE.exec(b) - reE.exec(a))
                  .reduce((res, str, i) => { 
                      let gap = reE.exec(array[i - 1]) - reE.exec(str);
                      if(gap > 0)
                          while(--gap) res.push(0);
                      res.push(+reS.exec(str));
                      return res;
                  }, []);

console.log("Sorted array:", array); 
console.log("Result:", result);