我有以下数组。
var arr = ["1-5", "3-6", "2-4"];
有没有一种方法可以像这样排序:
var arr = ["1-5", "2-4", "3-6"]
我尝试过使用 jquery map 但不能,因为数组的值不是数字。
最佳答案
您可以使用sort功能
按第一个数字排序
arr.sort(function (a, b) {
// a.split('-') - split a string into an array - ['1', '5']
// a.split('-')[0] - get first element - '1'
// "+" converts string to number - 1
// the same for "b"
return +a.split('-')[0] - +b.split('-')[0];
});
按第二数字排序
arr.sort(function (a, b) {
return +a.split('-')[1] - +b.split('-')[1];
});
关于javascript - 按数组的值对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27861456/