Skip to content

JavaScript array sort method | Sorts items order of an Array

  • by

JavaScript array sort method is used to sorting Array items in the given order. A sorted Array can be any order (as per given/need) like, alphabetic or numeric, and either ascending or descending.

Note: Be default a sort() method sorts the values as strings in alphabetical and ascending order and changes the original array.

Syntax

arr.sort(compareFunction)

Parameters

A function that defines an alternative sort order but its and Optional.

Return Value:

It returns Array object, with the items sorted.

Examples of sorting an Array in JavaScript

Let’s see the multiple examples:-

Sort string Array

Example of JavaScript sort array of objects alphabetically.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var fruits = ["Banana", "Orange", "Apple", "Mango"];

	alert(fruits.sort());

    </script> 
      
    
</body> 
  
</html>

Output:

JavaScript sort array of objects alphabetically

Sort numbers in an array 

Using compareFunction.

Ascending order

var points = [4, 10, 1, 5, 2, 1];
points.sort(function(a, b){return a-b});

Output: 1,1,2,4,5,10

Descending order

var points = [4, 10, 1, 5, 2, 1];
points.sort(function(a, b){return b-a});

Output: 10,5,4,2,1,1

Q: How to JavaScript sort an array of objects by date?

Answer: follow this approach to sort dates in JS.

<!DOCTYPE html> 
<html>
  
<body> 
    <script type="text/javascript"> 

    var array1 = [{id: 1, date:'Mar 12 2012 10:00:00 AM'}, {id: 2, date:'Mar 8 2012 08:00:00 AM'}];


	array1.sort(function(a, b) {
    	var c = new Date(a.date);
    	var d = new Date(b.date);
    	return c-d;
		});
	

	console.log(array1);

    </script> 
      
    
</body> 
  
</html> 

Output:

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *