Sorting an array by price in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of objects that contains data about some houses and price like this −

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

We are required to write a JavaScript function that takes in one such array. The function should sort the array (either in ascending or in descending) order according to the price property of the objects (which currently is a string).

Example

The code for this will be −

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

Output

And the output in the console will be −

[
   {
      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 24-Nov-2020 10:52:24
Advertisements