在javascript中排序对象周日到周六

Posted

技术标签:

【中文标题】在javascript中排序对象周日到周六【英文标题】:sorting object Sunday to Saturday in javascript 【发布时间】:2016-07-05 04:12:06 【问题描述】:

大家好,我认识的每个人都曾多次问过这个问题,但我没有得到确切的答案。

// I have array of object like this
data=[
        // "sunday": 1, // << sunday is first day of week      
      DayOfWeek:"Saturday", TotalCount:30,
      DayOfWeek:"Friday", TotalCount:10,
      DayOfWeek:"Monday", TotalCount:23,
      DayOfWeek:"Sunday", TotalCount:18, 
      DayOfWeek:"Wednesday", TotalCount:20        
    ];


// I need sorted like this:
data=[
        // "sunday": 1, // << sunday is first day of week
      DayOfWeek:"Sunday", TotalCount:18,  
      DayOfWeek:"Monday", TotalCount:23,
      DayOfWeek:"Wednesday", TotalCount:20,
      DayOfWeek:"Friday", TotalCount:10,
      DayOfWeek:"Saturday", TotalCount:30  
    ];

我试过这个,但我无法得到预期的结果。 它通过像

这样的字母开始给我一个排序数组

星期五,星期六。

var 排序器 = // "sunday": 1, //

  var result= data.sort(function sortByDay(a, b) 
    var day1 = a.DayOfWeek.toLowerCase();
    var day2 = b.DayOfWeek.toLowerCase();
    return sorter[day1] > sorter[day2];
  );

请帮助我,在此先感谢。

【问题讨论】:

【参考方案1】:

您可以使用订单对象对其进行排序,就像您已经拥有的那样,但您需要区别

return order[a.DayOfWeek] - order[b.DayOfWeek];

作为排序回调的返回值。

var data = [ DayOfWeek: "Saturday", TotalCount: 30 ,  DayOfWeek: "Friday", TotalCount: 10 ,  DayOfWeek: "Monday", TotalCount: 23 ,  DayOfWeek: "Sunday", TotalCount: 18 ,  DayOfWeek: "Wednesday", TotalCount: 20 ],
    order =  Sunday: 1, Monday: 2, Tuesday: 3, Wednesday: 4, Thursday: 5, Friday: 6, Saturday: 7 ;

data.sort(function (a, b) 
    return order[a.DayOfWeek] - order[b.DayOfWeek];
);
document.write('<pre>' + JSON.stringify(data, 0, 4) + '</pre>');

【讨论】:

感谢@nina,它工作得很好,非常感谢【参考方案2】:

没有任何内置函数,但制作解决方案应该不会太难。这是一个例子:

function s(a,b)
    return daysOfWeek.indexOf(a) - daysOfWeek.indexOf(b); // basic sort function that compares the indexes of the two days

var inputArray = ["Saturday", "Monday", "Sunday", "Tuesday"]; // input
var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; // array of days sorted
console.log(inputArray.sort(s)); // output

【讨论】:

以上是关于在javascript中排序对象周日到周六的主要内容,如果未能解决你的问题,请参考以下文章

java判断是不是是周六周日

本月周六周日LIST集合

用javascript计算任意两个日期之间的工作日(去掉周六周日),不用while循环,而是用for循环

JAVA 取五个工作日后的日期(仅排除周六周日)

javascript 从Date中获取星期几

如何获取一个月日历视图的第一天和最后一天(周日-周六)