Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

เรียง nested array ของอ็อบเจ็กต์ตามวันที่ - JavaScript

JSON มี nested array DATA ต้องการเรียงตาม DutyStart

ตัวอย่างโค้ด

const arr = {
  "DATA": [
    { "BookingID": "9513", "DutyStart": "2016-02-11 12:00:00" },
    { "BookingID": "91157307", "DutyStart": "2016-02-11 13:00:00" },
    { "BookingID": "95117317", "DutyStart": "2016-02-11 13:30:00" },
    { "BookingID": "957266", "DutyStart": "2016-02-12 19:15:00" },
    { "BookingID": "74", "DutyStart": "2016-02-11 12:21:00" }
  ]
};

const sortByDate = arr => {
  const sorter = (a, b) => {
    return new Date(a.DutyStart).getTime() - new Date(b.DutyStart).getTime();
  };
  arr["DATA"].sort(sorter);
  return arr;
};

console.log(sortByDate(arr));

ผลลัพธ์

{
  DATA: [
    { BookingID: '9513', DutyStart: '2016-02-11 12:00:00' },
    { BookingID: '74', DutyStart: '2016-02-11 12:21:00' },
    { BookingID: '91157307', DutyStart: '2016-02-11 13:00:00' },
    { BookingID: '95117317', DutyStart: '2016-02-11 13:30:00' },
    { BookingID: '957266', DutyStart: '2016-02-12 19:15:00' }
  ]
}

คำอธิบาย: เข้าถึง arr["DATA"] ใช้ sort() กับ comparator แปลง DutyStart เป็น Date แล้ว getTime() เปรียบเทียบ timestamp เรียงเก่าไปใหม่ (ascending) สำหรับ descending ให้สลับ a,b