javascript - 按自定义变量对数组排序

标签 javascript jquery arrays sorting

$("#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/

相关文章:

javascript - JS 初学者寻求关于非常短的函数的帮助

javascript - 在 Canvas HTML5 和 Fabric js 中的图像上添加删除图标

javascript - 带有点击事件的 stopPropagation()

javascript - 如何使用事件监听器单击函数来使用 javascript 显示和隐藏数组中的图像

php - 将配置(文本文件)转换为多维数组

javascript - 颜色选择器插件脚本导入导致意外标记

javascript - 推荐一个同时处理日期和时间的 JS 日历小部件?

javascript - 通过 data-* 属性删除行不起作用,为什么?

javascript - 浏览器加载事件后按连续顺序加载 JavaScript

javascript - 删除嵌套在对象内部的数组项