如何根据任意对象值对数组进行排序?

时间:2017-02-16 14:22:01

标签: javascript jquery arrays sorting time

我有一些基于工作日的数据如下:

[{
    "dayOfWeek": "TUESDAY",
    "startTime": "19:30:00",
    "endTime": "21:15:00"
}, {
    "dayOfWeek": "SATURDAY",
    "startTime": "19:15:00",
    "endTime": "21:00:00"
}, {
    "dayOfWeek": "FRIDAY",
    "startTime": "19:00:00",
    "endTime": "20:15:00"
}, {
    "dayOfWeek": "THURSDAY",
    "startTime": "19:15:00",
    "endTime": "20:30:00"
}, {
    "dayOfWeek": "WEDNESDAY",
    "startTime": "19:30:00",
    "endTime": "20:45:00"
}, {
    "dayOfWeek": "SUNDAY",
    "startTime": "19:30:00",
    "endTime": "20:45:00"
}, {
    "dayOfWeek": "MONDAY",
    "startTime": "19:30:00",
    "endTime": "21:00:00"
}]

但是,此数据来自具有不规则排序的API,这是不可信任的。我需要使用从MONDAY到SUNDAY的值来降序这个数组。我怎样才能做到这一点?我假设我必须设置某种地图进行查找?

1 个答案:

答案 0 :(得分:1)

您可以使用一个对象,其中包含日期和值以进行排序。

var array = [{ dayOfWeek: "TUESDAY", startTime: "19:30:00", endTime: "21:15:00" }, { dayOfWeek: "SATURDAY", startTime: "19:15:00", endTime: "21:00:00" }, { dayOfWeek: "FRIDAY", startTime: "19:00:00", endTime: "20:15:00" }, { dayOfWeek: "THURSDAY", startTime: "19:15:00", endTime: "20:30:00" }, { dayOfWeek: "WEDNESDAY", startTime: "19:30:00", endTime: "20:45:00" }, { dayOfWeek: "SUNDAY", startTime: "19:30:00", endTime: "20:45:00" }, { dayOfWeek: "MONDAY", startTime: "19:30:00", endTime: "21:00:00" }];

array.sort(function (a, b) {
    var sort = { MONDAY: 1, TUESDAY: 2, WEDNESDAY: 3, THURSDAY: 4, FRIDAY: 5, SATURDAY: 6, SUNDAY: 7 };
    return sort[a.dayOfWeek] - sort[b.dayOfWeek];
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }