Array.sort() - เรียงลำดับ Array
sort() เรียง Array In-place ตาม Unicode Code Point โดยค่าเริ่มต้น (String) ต้องส่ง Compare Function สำหรับตัวเลขหรือ Object
ตัวอย่าง: เรียง Object ตามอายุ (Death - Birthdate) เรียงมากไปน้อย (Descending)
<script>
var persons = [
{ name: 'rajesh', birthdate: 1845, death: 1875 },
{ name: 'Bharat', birthdate: 1909, death: 1917 },
{ name: 'baba', birthdate: 1950, death: 1972 },
{ name: 'Tanish', birthdate: 2039, death: 2067 },
{ name: 'rahim', birthdate: 1989, death: 2049 }
];
var sortedArray = persons.sort(function(a, b) {
var ageA = a.death - a.birthdate;
var ageB = b.death - b.birthdate;
return ageB - ageA; // Descending: มากไปน้อย
});
console.log(sortedArray);
</script>
ผลลัพธ์ (Console)
{name: "rahim", birthdate: 1989, death: 2049} // อายุ 60
{name: "rajesh", birthdate: 1845, death: 1875} // อายุ 30
{name: "Tanish", birthdate: 2039, death: 2067} // อายุ 28
{name: "baba", birthdate: 1950, death: 1972} // อายุ 22
{name: "Bharat", birthdate: 1909, death: 1917} // อายุ 8
ตัวอย่าง: เรียงน้อยไปมาก (Ascending)
persons.sort((a, b) => (a.death - a.birthdate) - (b.death - b.birthdate));
Compare Function กฎ
- Return < 0 → a มาก่อน b
- Return > 0 → b มาก่อน a
- Return 0 → คงตำแหน่ง