Skip to content

Sort array of objects JavaScript by number | Example code

  • by

Simply you can use the JavaScript sort function to sort an array of objects by number. It will work in Angular(TypeScript) also.

When sorting numbers, you can simply use the compact comparison:

myArray.sort((n1,n2) => n1 - n2);

Sort array of objects JavaScript by number

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    var data = [
    {
     title: 'Shirt',
     position: 3
   },
   {
     title: 'Ball',
     position: 1,
   }
   ];

   data.sort(function(a, b) { 
    return a.position- b.position;
  })

   console.log(data);
 </script>

</body>
</html> 

Output:

Sort array of objects JavaScript by number

Or

Use Array.prototype.sort (doc) and pass the compare function as you want:

var data = [
 {
   title: 'Shirt',
   position: 3
 },
 {
   title: 'Ball',
   position: 1,
 },
 // add for actually seeing the correct result
 {
   title: 'Cake',
   position: 2,
 }
];

function compareFunction(a,b){
  if(a.position > b.position)
    return 1;
  else
    return -1;
}

data.sort(compareFunction);

console.log(data);

How to sort an array of objects in ascending order of number?

Answer: Use the sort method with compare function to get ascending order of numbers.

  <script>
    var arr = [
    { id: 3, name: "raj" },
    { id: 2, name: "john" },
    { id: 5, name: "kelvin" } 
    ];

    var sortedArray = arr.sort(function(a, b) {
      return a.id - b.id 
    });

    console.log(sortedArray)
  </script>

Output:

0: Object { id: 2, name: "john" }
​
1: Object { id: 3, name: "raj" }
​
2: Object { id: 5, name: "kelvin" }

Do 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