JavaScript Array Sort() Method with Example

JavaScript Array sort() method sorts elements of an array in a specific order. This method makes very easy to reorder an array.

For example, you can use sort() method to arrange an array of numbers in numerical order, and an array of strings in alphabetical order such as a list of names.

Array.sort() method sorts elements of an array in its own place and returns sorted array. That is, the sort() method overwrites the original array. It does not create a new array.

The sort() method sorts the array elements in either alphabetic or numeric, and either ascending (up) or descending (down).

JavaScript Array Sort Method Syntax


The general syntax to define sort() method in JavaScript is as:

array.sort(compareFunction);

In the above function, compareFunction is an optional. It is used to define a custom sort order. This function returns a negative, zero, or positive value, depending on arguments.

When sort() method compares two values, it sends the values to the compare function, and sorts the values according to the outcome (negative, zero, positive) value.

If we do not specify “compareFunction”, JavaScript interpreter sorts elements of an array by converting them to strings and comparing strings in lexicographic order.

For example, “80” comes before “9” in lexicographic order, but in a numeric sort 9 comes before 80. As the numbers are converted to strings, so “80” comes before “9” in the Unicode order.

If an array has undefined elements, JavaScript interpreter sorts them at the end of an array.

Sorting Array of Elements in Alphabetical Order


If you call sort() method with no arguments, the array sort() method sorts elements of an array in alphabetical order. Let’s take an example program based on it.

Program code 1:

<script>
// Create an array of elements.
  const names = ["Paul", "Tripti", "Sarah", "Ivaan", "Rashmi"];
  const n = names.sort(); // passing no arguments.
  document.write("Sorted names in alphabetical order: ", "<br>");
  document.write(n);
</script>
Output:
     Sorted names in alphabetical order:
     Ivaan,Paul,Rashmi,Sarah,Tripti

Program code 2:

<script>
// Create an array of elements.
  const names = ["Paul", "Tripti", "Sarah", "Ivaan", "Rashmi"];
  names.sort(); // passing no arguments.
  document.write("List of names in alphabetical order: ", "<br>");
  for(let i = 0; i < names.length; i++)
  {
     document.write(names[i], "<br />");
  }
</script>
Output:
     List of names in alphabetical order:
     Ivaan
     Paul
     Rashmi
     Sarah
     Tripti

Sorting Array Elements in Custom Order


To sort an array of element in a specific order other than alphabetical order, we must pass a comparison function as an argument to sort() method.


The comparison function gets two distinct array elements and compares them. It returns a number that decides which of its two argument values will appear first in the sorted array. That is, the number decides the result.

The comparison function will return a number less than zero if the first value will sort before the second.

If the first value sorts after the second in sorted array, the function will return a number greater than zero.

If both values are equivalent, the comparison function will return 0. Let’s write a general comparison function.

function compare(a, b) {
   if (a > b) {
     return 1;
   } else if (b > a) {
     return -1;
   } else {
     return 0;
   }
}

Let’s take an example program to sort an array of elements in numerical order rather than alphabetical order.

Program code 3:

<script>
  let nums = [55, 5, 1111, 222];
// Sorting array elements in alphabetical order.
  let x = nums.sort();
  document.write("Alphabetical order: ", "<br>");
  document.write(x);
  document.write("<br />");

// Sorting array elements numerical.
  document.write("Numerical order: ", "<br>");
  let y = nums.sort(function(a, b) {
     return a - b; // returns < 0, 0, or > 0.
   }
  );
  document.write(y);
</script>
Output:
      Alphabetical order:
      1111,222,5,55
      Numerical order:
      5,55,222,1111

Sorting Array of Numbers in Ascending Order


Let’s create a JavaScript program to sort an array of numbers in ascending order using a comparison function.


Program code 4:

<script>
  let nums = [555, 30, 5, 40, 20, 10];
// Sorting array elements in ascending order.
  document.write("Ascending order: ", "<br>");
  let y = nums.sort(function(a, b) {
     return a - b; // returns < 0, 0, or > 0.
   }
  );
document.write(y);
</script>
Output:
     Ascending order:
     5,10,20,30,40,555

Sorting Array Elements in Descending Order


Let’s create a JavaScript program to sort an array of numbers in descending order using a comparison function.

Program code 5:

<script>
  let nums = [555, 30, 5, 40, 20, 10];
// Sorting array elements in descending order.
  document.write("Descending order: ", "<br>");
  let y = nums.sort(function(a, b) {
     return b - a; // returns < 0, 0, or > 0.
    }
  );
document.write(y);
</script>
Output:
     Descending order:
     555,40,30,20,10,5

Sort Array Elements in Case-insensitive Alphabetical Order


We can also perform a case-insensitive alphabetical order using a comparison function. Let’s take an example program based on it.

Program code 6:

<script>
  let colors = ["Red", "pink", "green", "Brown"];
// Sorting array elements in case-sensitive alphabetical order.
  document.write("Case-sensitive sort: ", "<br>");
  let x = colors.sort();
  document.write(x);
  document.write("<br/>");

  document.write("Case-insensitive sort: ","<br/>");
  let y = colors.sort(function(a, b) {
     let p = a.toLowerCase();
     let q = b.toLowerCase();
     if(p < q) return -1;
     if(p > q) return 1;
      return 0;
     }
  );
  document.write(y);
</script>
Output:
      Case-sensitive sort:
      Brown,Red,green,pink
      Case-insensitive sort:
      Brown,green,pink,Red

Sorting an Array of Objects by a Property Value


We can sort an array that contains objects based on the property values. Let’s take an example program in which we will sort an array of objects with people’s information.

Program code 7:

<script>
const people = [
    {name: "Tripti", age: 23},
    {name: "Ivaan", age: 5},
    {name: "John", age: 20},
    {name: "Tammy", age: 19}
];
// Sort the people from youngest to oldest by age.
  people.sort(function(a, b) {
     if(a.age < b.age) {
         return -1;
     } else if(a.age > b.age) {
         return 1;
     } else {
         return 0;
     }
   });
console.log(people);
</script>
Output:
      Ivaan, Tammy, John, Tripti

We can also write a much shorter comparison function like this:

people.sort(function(a, b) {
// Subtract ages to sort from youngest to oldest.
   return a.age - b.age;  
});

You can also write the above code with compact arrow syntax like this:

people.sort((a, b) => a.age - b.age);

We can also write a comparison function to sort by name as:

// Sort the people by name.
people.sort(function(a, b) {
const nameA = a.name.toUpperCase(); // ignore upper and lowercase
const nameB = b.name.toUpperCase(); // ignore upper and lowercase
if(nameA < nameB) {
    return -1;
} else if (nameA > nameB) {
   return 1;
} else {
   return 0;
}
});
console.log(people);

// Using arrow function.
people.sort((a, b) => a.name.localeCompare(b.name));
console.log(people); 
Output:
      Ivaan, John, Tammy, Tripti

Program to Find Lowest Number and Highest Number


Let’s write a JavaScript program to find the lowest number and highest number among different numbers.

Program code 8:

<script>
const numbers = [40, 100, 10, 5, 25, 15];
// Sort the numbers in ascending order:
  numbers.sort(function(a, b) {
     return a - b;
  });
document.write("Lowest number: " +numbers[0]);
</script>
Output:
     Lowest number: 5

Program code 9:

<script>
 const numbers = [40, 100, 10, 5, 25, 15];
// Sort the numbers in descending order:
  numbers.sort(function(a, b) {
      return b - a;
  });
document.write("Highest number: " +numbers[0]);
</script>
Output:
     Highest number: 100

We can also write the code for the above program like this:

Program code 10:

<script>
const numbers = [40, 100, 10, 5, 25, 15];

// Sort the numbers in ascending order:
numbers.sort(function(a, b) {
return a - b;
});
document.write("Highest number: " +numbers[numbers.length - 1]);
</script>

Browser Support

The sort() method is an important feature of ECMAScript1 (ES1). All browsers fully support ES1 (JavaScript 1997).


In this tutorial, you learned JavaScript array sort() method with various example programs. Hope that you will have understood the basic concepts of sort() method in JavaScript.
Thanks for reading!!!
Next ⇒ JavaScript array slice() method⇒ Prev Next ⇐

Please share your love