$("#show_times_available_" + pos).find("td span").parent().each(function(){
array.push($(this).attr("id"));
array = array.sort();
});
我的数组获取所有元素并获取它们的 ID 并将其插入一个数组,这样我的数组最终将成为;
[ "mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0" ];
我想做的是每次将新元素插入数组时将这些元素排序为(星期一、星期二、星期三等...)。这样我的数组就会变成;
[ "mon_0600-0", "tue_0300-0", "wed_0700-0", "thu_0600-0", "thu_0700-0", "sun_0700-0" ];
使用基本的 sort()
函数将按字母顺序排列,我知道 sort()
函数可以接受另一个函数。我只是不确定如何在 vanilla javascript 或 jQuery 中设置它。是否有 CASE THEN 或使用 when()
和 then()
对这些进行排序的方法?我在谷歌和 SO 周围搜索过,但一无所获。
最佳答案
您需要将自定义函数传递给 sort()
正如你所说。在这里,需要将日期和时间分开,然后返回日期部分和时间部分的比较(如果日期相同):
var arr = ["mon_0600-0", "sun_0700-0", "thu_0600-0", "thu_0700-0", "tue_0300-0", "wed_0700-0"];
// store the order of the days
var days = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
var arrSorted = arr.sort(function(a, b) {
// a and b are two times to compare
// split each into days and times, e.g ["mon", "0600-0"]
var aSplit = a.split("_");
var bSplit = b.split("_");
// get the index of the days to compare
var dayA = days.indexOf(aSplit[0]);
var dayB = days.indexOf(bSplit[0]);
// if days are the same, compare the times using normal String comparison
// if days are different, return the comparison of their position in the array
return dayA == dayB ?
aSplit[1].localeCompare(bSplit[1])
: dayA - dayB;
});
console.log(arrSorted);
关于javascript - 按自定义变量对数组排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35452294/