다음과 같은 일부 주택 및 가격에 대한 데이터를 포함하는 객체 배열이 있다고 가정합니다.
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'
}
]