javascript : Sorting an array of objects

In this tutorial learn how to sorting an array of objects using javascript function sort(),

lets say your array doesn't contain just simple numeric or string values, but objects with properties instead:

The sort() method can be used to sort the array based on the values of one of these properties, such as sorting the array by age.



Sort by user age

Lets start by sorting the user array by their ages (ascending). Here's the comparison function that does this:


<body onload="javascript:sort_arr()">
<script type="text/javascript">
  function sort_arr() {
   var user=[]
       user[0]={name:"Ghanshyam", age:30}
       user[1]={name:"Nakiya", age:15}
       user[2]={name:"Jack", age:50}
       user[3]={name:"Taylor", age:58}
        user.sort(function(a, b){
          return a.age-b.age;
       })
      alert(JSON.stringify(user));
     }
</script>
</body>


Sort by user Name

Lets start by sorting the user array by their name (ascending). Here's the comparison function that does this:


<body onload="javascript:sort_arr()">
<script type="text/javascript">
  function sort_arr() {
   var user=[]
       user[0]={name:"Ghanshyam", age:30}
       user[1]={name:"Nakiya", age:15}
       user[2]={name:"Jack", age:50}
       user[3]={name:"Taylor", age:58}
        user.sort(function(a, b){
          var A=a.name.toLowerCase(), B=b.name.toLowerCase()
         if (A < B) //sort string ascending
        return -1 
         if (A > B)
         return 1
         return 0 //default return value (no sorting)
       })
      alert(JSON.stringify(user));
     }
</script>
</body>




2 comments:

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...