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

การเรียงลำดับอาร์เรย์ด้วยสองเกณฑ์ใน JavaScript


ให้อาร์เรย์ต่อไปนี้เรียงตาม date และ isImportant ออบเจ็กต์ที่ isImportant เป็น true จะอยู่หน้ากว่าที่เป็น false และทั้งสองกลุ่มเรียงตาม date

อาร์เรย์ของเรา −

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, }, ];

ใช้ sort() ดังนี้เพื่อให้ได้ผลลัพธ์ที่ต้องการ −

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() รับ a, b เป็นสองสมาชิก คืน -1 หมายถึง a อยู่หน้า b, คืน 1 หมายถึง b อยู่หน้า a, คืน 0 ไม่เปลี่ยน ตรวจสอบ isImportant ก่อน ไม่ใช่ค่อยเรียงตาม date

ตัวอย่าง

โค้ดเต็ม −

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, }, ]; 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;    } }); console.log(array);

ผลลัพธ์

ผลลัพธ์ใน Console จะเป็น −

[    { id: 3, date: 591080424000, isImportant: true },{ id: 5, date: 591020225525, isImportant: true },    { id: 4, date: 591080225525, isImportant: false },{ id: 2, date: 591080224000, isImportant: false },    { id: 1, date: 591020824000, isImportant: false } ]