Sorting an array of objects by property values - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

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

We are required to write a JavaScript function that sorts the objects by the price property in ascending or descending order.

Example

Following is the code −

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);

Output

This will produce the following output on console −

[
 {
   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'
 }
]
raja
Published on 01-Oct-2020 13:51:20
Advertisements