Chúng ta có một mảng như sau:
const arr = [
{ year: 2020, month: 'January' },
{ year: 2017, month: 'March' },
{ year: 2010, month: 'January' },
{ year: 2010, month: 'December' },
{ year: 2020, month: 'April' },
{ year: 2017, month: 'August' },
{ year: 2010, month: 'February' },
{ year: 2020, month: 'October' },
{ year: 2017, month: 'June' }
]Cần sắp xếp mảng này theo năm tăng dần. Nếu hai đối tượng có cùng năm, sắp xếp theo tháng (Tháng 1, 2, 3...).
Mã hoàn chỉnh cho bài toán sắp xếp này:
Ví dụ
const arr = [
{ year: 2020, month: 'January' },
{ year: 2017, month: 'March' },
{ year: 2010, month: 'January' },
{ year: 2010, month: 'December' },
{ year: 2020, month: 'April' },
{ year: 2017, month: 'August' },
{ year: 2010, month: 'February' },
{ year: 2020, month: 'October' },
{ year: 2017, month: 'June' }
];
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const sorter = (a, b) => {
if (a.year !== b.year) {
return a.year - b.year;
} else {
return months.indexOf(a.month) - months.indexOf(b.month);
}
};
arr.sort(sorter);
console.log(arr);Chúng ta kiểm tra nếu năm khác nhau thì sắp xếp theo năm, nhưng khi năm giống nhau thì kiểm tra tháng nhờ mảng months tùy chỉnh, giúp các đối tượng cùng năm được sắp xếp theo tháng.
Kết quả
Đầu ra trong console sẽ là:
[
{ year: 2010, month: 'January' },
{ year: 2010, month: 'February' },
{ year: 2010, month: 'December' },
{ year: 2017, month: 'March' },
{ year: 2017, month: 'June' },
{ year: 2017, month: 'August' },
{ year: 2020, month: 'January' },
{ year: 2020, month: 'April' },
{ year: 2020, month: 'October' }
]