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

การจัดเรียงอาร์เรย์ออบเจกต์ให้ flag: false อยู่หน้าสุดใน JavaScript

คำอธิบาย

จัดเรียงอาร์เรย์ออบเจกต์ที่มีคุณสมบัติ flag ให้ค่าที่เป็น false อยู่หน้าสุด พร้อมรักษาลำดับเดิมของกลุ่มเดียวกัน

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

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);

ผลลัพธ์

[ { 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 } ]