Data Structure
 Networking
 RDBMS
 Operating System
 Java
 MS Excel
 iOS
 HTML
 CSS
 Android
 Python
 C Programming
 C++
 C#
 MongoDB
 MySQL
 Javascript
 PHP
- Selected Reading
 - UPSC IAS Exams Notes
 - Developer's Best Practices
 - Questions and Answers
 - Effective Resume Writing
 - HR Interview Questions
 - Computer Glossary
 - Who is Who
 
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.
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
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}Advertisements