Skip to content

Sort array of objects JavaScript alphabetically | Example code

  • by

Use Array sort with function to Sort an array of objects JavaScript alphabetically. You have to use the sort() method and provide a custom comparator function that compares the values of the properties you want to sort by.

Sort array of objects JavaScript alphabetically

Simple example code sort car list by its name property in Object.

<!DOCTYPE html>
<html>
<body>

  <script>
    cars = [{
      name: 'ab',
      description: 'this is car1 description'
    },{
      name: 'cd',
      description: 'this is car2 description'
    },{
      name: 'car3',
      description: 'this is car3 description'
    },{
      name: 'aaa',
      description: 'this is car4 description'
    },{
     name: 'car5',
     description: 'this is car5 description'
   }];

   cars.sort((a,b) => a.name > b.name ? 1 : -1)

   console.log(cars)

 </script>

</body>
</html> 

Output:

Sort array of objects JavaScript alphabetically

Sort objects in an array alphabetically based on one property. Changing the case (to upper or lower) ensures a case-insensitive sort.

myArray.sort(function (a, b) {
  var textA = a.name.toUpperCase();
  var textB = b.name.toUpperCase();

  return textA.localeCompare(textB);
});

Using localeCompare() and sort() Function

var a = [
	{FirsName:"Ellie", LastName:"Williams"},
	{FirstName:"Lara", LastName : "Croft"}
];
function SortArray(x, y){
    return x.LastName.localeCompare(y.LastName);
}
var s = a.sort(SortArray);
console.log(s);

Output:

0: Object { FirstName: "Lara", LastName: "Croft" }
​
1: Object { FirsName: "Ellie", LastName: "Williams" }

Comment if you have any doubts or suggestions on this JS array sort 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