sorting object Sunday to Saturday in javascript

Hello Everyone i know this question is asked several time but i am not getting exact answer to my question.

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

I tried this one but I am not able to get the expected result. it is giving me a sorted array by starting alphabet like

Friday, Saturday.

var sorter = { // "sunday": 1, // << sunday is first day of week "sunday": 1, "monday": 2, "tuesday": 3, "wednesday": 4, "thursday": 5, "friday": 6, "saturday": 7 }

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

Please help me, Thanks in advance.


You can sort it with an object for the order, as you already had, but you need the difference

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

as a return value for the sort callback.

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

There aren't any built-in functions, but it shouldn't be too hard to make a solution. Here's an example:

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