假设我有一个数组:
const styles = require('./styles')
const promise = styles.onLoad('foo.css', 'bar.css')
promise.then(() => console.log('Styles loaded!'))
如何对数组进行排序,使每个数组元素中的最后一个数字按降序排列?那就是:
["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"]
我已经检查了各种["Team B, 7, 1, 14","Team A, 6, 2, 12","Team C, 4, 4, 8"]
,但我无法弄清楚如何根据这种特定情况定制它们。
答案 0 :(得分:4)
使用正则表达式获取Array#sort()
let reg = /\d+$/;
let arr = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
arr.sort((a, b) => reg.exec(b) - reg.exec(a));
console.log(arr)
答案 1 :(得分:2)
您必须定义自己的比较功能
var arr = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
function compare(a,b){
var vala = a.split(',').pop();
var valb = b.split(',').pop();
return valb-vala;
}
arr.sort(compare);
console.log(arr);

答案 2 :(得分:1)
基本上,您需要做的就是提取最后一个数字,然后在您的比较中使用它:
var myArray = ["Team A, 6, 2, 12","Team B, 7, 1, 14","Team C, 4, 4, 8"];
function sorter(item1, item2) {
const split1 = item1.split(",");
const split2 = item2.split(",");
const num1 = split1[split1.length - 1] || 0;
const num2 = split2[split2.length - 1] || 0;
return num2 - num1;
}
myArray.sort(sorter)
console.log(myArray)