Sắp xếp mảng object theo date và isImportant. Object có isImportant: true xếp trước, sau đó cả hai nhóm đều sắp theo date giảm dần.
Mảng gốc
const array = [{ id: 545, date: 591020824000, isImportant: false }, { id: 322, date: 591080224000, isImportant: false }, { id: 543, bdate: 591080424000, isImportant: true }, { id: 423, date: 591080225525, isImportant: false }, { id: 135, date: 591020225525, isImportant: true }, ];
Hàm so sánh
array.sort((a, b) => { if(a.isImportant && !b.isImportant){ return -1; } else if(!a.isImportant && b.isImportant){ return 1; } else { return b.date - a.date; } });
Callback sort nhận 2 phần tử a,b. Trả về âm: a trước b. Dương: b trước a. 0: giữ nguyên.
Logic: Ưu tiên isImportant. Nếu cùng nhóm, sắp theo date giảm dần (mới nhất trước).
Kết quả
[ { id: 543, date: 591080424000, isImportant: true }, { id: 135, date: 591020225525, isImportant: true }, { id: 423, date: 591080225525, isImportant: false }, { id: 322, date: 591080224000, isImportant: false }, { id: 545, date: 591020824000, isImportant: false } ]
Lưu ý: Object id=543 có key bdate typo, nên b.date là undefined, kết quả sort có thể sai. Cần đảm bảo dữ liệu nhất quán.