Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Sắp xếp mảng đối tượng theo giá trị thuộc tính - JavaScript

Cho mảng đối tượng như sau:

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" }
];

Yêu cầu: viết hàm sắp xếp các đối tượng theo thuộc tính price tăng dần hoặc giảm dần.

Mã thực hiện

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) => parseFloat(a.price) - parseFloat(b.price));
};
sortByPrice(homes);
console.log(homes);

Kết quả

[
  { 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' }
]