เรามีอาร์เรย์แบบนี้
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' }]เราต้องจัดเรียงอาร์เรย์นี้ตามปีในลำดับเพิ่มขึ้น (ascending) นอกจากนี้ หากมีออบเจกต์สองตัวที่มีค่า year เหมือนกัน เราต้องจัดเรียงปีเหล่านั้นตามเดือน (ม.ค. แล้ว ก.พ. แล้ว มี.ค. และไปเรื่อยๆ)
มาเขียนโค้ดสำหรับการจัดเรียงนี้ โค้ดเต็มรูปแบบจะเป็นดังนี้
ตัวอย่าง
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);เราตรวจสอบว่าปีต่างกันหรือไม่ ถ้าต่างกันจัดเรียงตามปี แต่ถ้าปีเหมือนกัน ตรวจสอบเดือนด้วยช่วยจากอาร์เรย์ months ที่กำหนดเอง และด้วยวิธีนี้ ออบเจกต์ที่มีปีเดียวกันจะถูกจัดเรียงตามเดือน
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[ { 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' } ]