สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ที่มีข้อมูลเกี่ยวกับบ้านและราคาแบบนี้:
const arr = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
},
{
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
},
{
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
เราต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์ดังกล่าว ฟังก์ชันควรจัดเรียงอาร์เรย์ (ไม่ว่าจะเป็นลำดับเพิ่มหรือลด) ตามคุณสมบัติ price ของอ็อบเจ็กต์ (ซึ่งปัจจุบันเป็นสตริง)
ตัวอย่างโค้ด
โค้ดสำหรับทำสิ่งนี้คือ:
const arr = [
{
"h_id": "3",
"city": "Dallas",
"state": "TX",
"zip": "75201",
"price": "162500"
},
{
"h_id": "4",
"city": "Bevery Hills",
"state": "CA",
"zip": "90210",
"price": "319250"
},
{
"h_id": "5",
"city": "New York",
"state": "NY",
"zip": "00010",
"price": "962500"
}
];
const eitherSort = (arr = []) => {
const sorter = (a, b) => {
return +a.price - +b.price;
};
arr.sort(sorter);
};
eitherSort(arr);
console.log(arr);
ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้:
[
{
h_id: '3',
city: 'Dallas',
state: 'TX',
zip: '75201',
price: '162500'
},
{
h_id: '4',
city: 'Bevery Hills',
state: 'CA',
zip: '90210',
price: '319250'
},
{
h_id: '5',
city: 'New York',
state: 'NY',
zip: '00010',
price: '962500'
}
]