Mô tả bài toán
Sắp xếp mảng đối tượng có thuộc tính flag (boolean) sao cho false lên trước, true sau, giữ nguyên thứ tự trong mỗi nhóm (stable sort).
Ví dụ minh họa
const arr = [
{flag: true, other: 1},
{flag: true, other: 2},
{flag: false, other: 3},
{flag: true, other: 4},
{flag: true, other: 5},
{flag: true, other: 6},
{flag: false, other: 7}
];
const sortByFlag = arr => {
const sorter = (a, b) => {
if (!a.flag && b.flag) return -1;
if (a.flag && !b.flag) return 1;
return a.other - b.other;
};
arr.sort(sorter);
};
sortByFlag(arr);
console.log(arr);
Kết quả
[
{ flag: false, other: 3 },
{ flag: false, other: 7 },
{ flag: true, other: 1 },
{ flag: true, other: 2 },
{ flag: true, other: 4 },
{ flag: true, other: 5 },
{ flag: true, other: 6 }
]
Cách viết ngắn gọn
arr.sort((a, b) => (a.flag === b.flag ? 0 : a.flag ? 1 : -1));
Lưu ý
sort() của JS không đảm bảo stable trước ES2019. Code gốc dùng other làm tie-breaker để đảm bảo thứ tự.