Sorting an array of objects by property values Sorting an array of objects by property values arrays arrays

Sorting an array of objects by property values


Sort homes by price in ascending order:

homes.sort(function(a, b) {    return parseFloat(a.price) - parseFloat(b.price);});

Or after ES6 version:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

Some documentation can be found here.

For descending order, you may use

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));


Here's a more flexible version, which allows you to create reusable sort functions, and sort by any field.

const sort_by = (field, reverse, primer) => {  const key = primer ?    function(x) {      return primer(x[field])    } :    function(x) {      return x[field]    };  reverse = !reverse ? 1 : -1;  return function(a, b) {    return a = key(a), b = key(b), reverse * ((a > b) - (b > a));  }}//Now you can sort by any field at will...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"}];// Sort by price high to lowconsole.log(homes.sort(sort_by('price', true, parseInt)));// Sort by city, case-insensitive, A-Zconsole.log(homes.sort(sort_by('city', false, (a) =>  a.toUpperCase())));