สมมติว่าเรามีอาร์เรย์ของออบเจกต์ดังนี้:
const homes = [
{
"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 homes = [
{ "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 sortByPrice = arr => {
arr.sort((a, b) => {
return parseFloat(a.price) - parseFloat(b.price);
});
};
sortByPrice(homes);
console.log(homes);
ผลลัพธ์
โค้ดนี้จะแสดงผลลัพธ์ดังต่อไปนี้บนคอนโซล:
[
{ 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' }
]