How to sort an array in JavaScript?Explain with example?


Sorting

Sorting is nothing but displaying elements in ascending or descending order. Array.sort() function is to sort the array according to the compare() function in JavaScript.

a) In the given program we are going to sort the array by  age property in descending order.

 Live Demo

Example

<html>
<body>
<script>
   var persons = [
                      { name: 'rajesh', birthdate: 1845, death: 1875 },
                      { name: 'Bharat', birthdate: 1909, death: 1917},
                      { name: 'baba', birthdate: 1950, death: 1972 },
                      { name: 'Tanish', birthdate: 2039, death: 2067 },
                      { name: 'rahim', birthdate: 1989, death: 2049 }
                 ]
   var sortedArray = persons.sort(function(a,b) {
   var lastPerson = a.death - a.birthdate;
   var nextPerson = b.death - b.birthdate;
   if (lastPerson > nextPerson) {
   return -1;
   } else {
   return 1;
   }
   });
   console.log(sortedArray);
</script>
</body>
</html>

Output in browser console

{name: "rahim", birthdate: 1989, death: 2049}
{name: "rajesh", birthdate: 1845, death: 1875}
{name: "Tanish", birthdate: 2039, death: 2067}
{name: "baba", birthdate: 1950, death: 1972}
{name: "Bharat", birthdate: 1909, death: 1917}


b) Here sorting is done so as to arrange the array in ascending order using age property

 Live Demo

Example

<html>
<body>
<script>
   var persons = [
                     { name: 'rajesh', birthdate: 1845, death: 1875 },
                     { name: 'Bharat', birthdate: 1909, death: 1917},
                     { name: 'baba', birthdate: 1950, death: 1972 },
                     { name: 'Tanish', birthdate: 2039, death: 2067 },
                     { name: 'rahim', birthdate: 1989, death: 2049 }
                 ]
   var sortedArray = persons.sort(function(a,b) {
   var lastPerson = a.death - a.birthdate;
   var nextPerson = b.death - b.birthdate;
   if (lastPerson < nextPerson) {
   return -1;
   } else
   {
   return 1;
   }
   });
   console.log(sortedArray);  
</script>
</body>
</html>

Output in browser console

{name: "Bharat", birthdate: 1909, death: 1917}
{name: "baba", birthdate: 1950, death: 1972}
{name: "Tanish", birthdate: 2039, death: 2067}
{name: "rajesh", birthdate: 1845, death: 1875}
{name: "rahim", birthdate: 1989, death: 2049}

Updated on: 30-Jul-2019

89 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements