Skip to content

Sort array of objects JavaScript | Example code

  • by

Use the sort method with the comparison function to Sort an array of objects in JavaScript. Use the < or > operator when comparing strings in your compare function.

Sort array of objects JavaScript

Simple example code sort data by the value of last_nom in JavaScript.

<!DOCTYPE html>
<html>
<body>
  <script>
   var objs = [ 
   { first_nom: 'Lazslo', last_nom: 'Jamf'     },
   { first_nom: 'Pig',    last_nom: 'Bodine'   },
   { first_nom: 'Pirate', last_nom: 'Prentice' }
   ];

   function compare( a, b ) {
    if ( a.last_nom < b.last_nom ){
      return -1;
    }
    if ( a.last_nom > b.last_nom ){
      return 1;
    }
    return 0;
  }

  objs.sort(compare);

  console.log(objs);

</script>
</body>
</html> 

Output:

Sort array of objects JavaScript

Sort an array of objects by numbers

The following example sorts the employees array by ages in ascending order using the inline function.

  <script>
   let employees = [
   {
    firstName: 'John',
    lastName: 'Doe',
    age: 27,
    joinedDate: 'December 15, 2017'
  },

  {
    firstName: 'Ana',
    lastName: 'Rosy',
    age: 25,
    joinedDate: 'January 15, 2019'
  },

  {
    firstName: 'Zion',
    lastName: 'Albert',
    age: 30,
    joinedDate: 'February 15, 2011'
  }
  ];

  employees.sort((a, b) => {
    return a.age - b.age;
  });

  console.log(employees)
</script>

Sorting an array of objects by property values

var 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 homes by price in ascending order:

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

Or after the ES6 version:

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

For descending order, you may use

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

Source: stackoverflow.com

Do comment if you have any doubts or suggestions on this JS array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading