在javascript中将对象从星期日到星期六排序

时间:2016-03-18 12:01:21

标签: javascript arrays sorting

大家好我知道这个问题有几次被问到,但我没有得到我问题的确切答案。



// 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}  
    ];
&#13;
&#13;
&#13;

我试过这个,但我能够得到预期的结果。 它通过satring字母表给出mi排序的数组,如

星期五,星期六。

  

var sorter = {           //&#34;星期日&#34;:1,//&lt;&lt;星期日是一周的第一天           &#34;星期日&#34;:1,           &#34;星期一&#34;:2,           &#34;周二&#34;:3,           &#34;周三&#34;:4,           &#34;星期四&#34;:5,           &#34;周五&#34;:6,           &#34;星期六&#34;:7         }

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

请帮助我,提前致谢

2 个答案:

答案 0 :(得分:8)

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

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>');

答案 1 :(得分:3)

没有任何内置功能,但解决方案不应太难。这是一个例子:

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