Giả sử chúng ta có mảng đối tượng chứa dữ liệu về nhà và giá như sau:
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"
}
];
Cần viết hàm nhận mảng như vậy. Hàm sắp xếp mảng (tăng dần hoặc giảm dần) theo thuộc tính price (hiện là chuỗi).
Ví dụ
Mã thực hiện như sau:
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);
Kết quả
Kết quả trong console sẽ là:
[
{
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'
}
]