Sort Array of Objects by Property Values in JavaScript



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'  } ]
Updated on: 2020-10-01T10:21:20+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close