JavaScript Array Sort

JavaScript Array Sort

4 mins read1K Views Comment
Chanchal
Chanchal Aggarwal
Senior Executive Content
Updated on May 14, 2024 14:11 IST

The JavaScript array.sort() method sorts the elements of an array in place and returns the sorted array. By default, it sorts elements as strings in ascending order, but a custom compare function can be provided to define alternative sorting behaviors, such as numerical sorting or complex object sorting based on specific properties.

2022_11_Array-Sort.jpg

In the JavaScript array, you have various items within a single variable. You need a method where those items can be sorted meaningfully. With JavaScript array sort, developers can sort the elements in a specific way. 

In this blog, we have discussed sorting in JavaScript arrays and related concepts. Let’s check it out. 

Want to be a certified JavaScript developer? Explore top free JavaScript certifications.

Table of Contents

Check out Online JavaScript Courses and Certifications

What is Sorting in JavaScript Array?

The sort() method sorts array elements and shows them in place. It can be in any order as per the required condition.

For instance- Ascending or descending order, alphabetical order, ranking, etc.

Example:


 
let names = ["John", "Michael", "Alena", "Niah"];
// sort the names array in ascending order
let sortedArray = names.sort();
console.log(sortedArray)
Copy code

// Output: 

[ 'Alena', β€˜John’, 'Michael', β€˜Niah' ]

In the above example, we have alphabetically sorted elements of the array in ascending order. 

Numeric

The sort() function, by default, sorts values as strings. Therefore, it shows the correct results for the strings, such as Alena comes before John.

However, when numbers are sorted in the form of strings, the results will be incorrect as strings cannot be changed. Let’s understand this with an example.

Example: 


 
let numbers = ["57", "20", "72", "89", "43"];
// sort the numbers array in ascending order
let sortedArray = numbers.sort();
console.log(sortedArray);
Copy code

Output:

20, 43, 57, 72, 8

In the above example, we have sorted numbers as strings. β€œ20” is bigger than β€œ43” because it begins with the number β€œ2”. 

The result is incorrect because of the sort() function. Nevertheless, we can fix this problem with a compare function. Let’s understand what is compare function.

Recommended online courses

Best-suited Programming courses for you

Learn Programming with these high-rated online courses

β‚Ή10 K
3 months
β‚Ή19.99 K
97 days
– / –
6 weeks
β‚Ή4 K
2 months
β‚Ή15 K
3 months
β‚Ή2.05 K
3 months
β‚Ή31.55 K
7 months
β‚Ή26 K
3 months

Compare Function in JavaScript Sort

The compare function sorts the items according to various attributes and in different orders. Based on the resulting requirement, the compare function should return a positive, zero, or negative value.

In the compare function, we subtract b from a to evaluate numbers instead of strings. 

In the below function, arrays are sorted in ascending order (if it does not have Infinity and NaN):

Syntax: 


 
function(a, b) (return a-b)
Copy code

To gain better clarity about the compare function, let us understand how it works with the help of an illustration.

JavaScript Array Push

How to Find the JavaScript Array Length

How Compare Function Works?

The sort () function compares two values and sends the values to the compare function, and sorts the values as per the returned (negative, positive, or zero) value. 

Whenever the result is negative, a is sorted before b.

Whenever the result is positive, b is sorted prior to a.

Furthermore, when the result is 0, the sort order of the two values will not be altered.

In the compare function, all the values in the array are compared, two values simultaneously (a, b).

Example:

When comparing 70 and 80, the sort() method uses the compare function(70, 80).

The function will calculate 70 – 80 (a – b), and the result will be negative (-10). Therefore, the sort function will declare (sort) 70 as a lower value than 80.

Difference between Java and JavaScript | Java vs Javascript

How to Use JavaScript Array Filter

Finding the Highest or Lowest Array Value

Array developers do not have built-in methods to evaluate the minimum and maximum values. However, they can use the index to sort an array and find the highest and lowest values.

Sorting Ascending- 


 
<button onclick="myFunction1()">Sort Alphabetically</button>
<button onclick="myFunction2()">Sort Numerically</button>
<p id="demo"></p>
<script>
const points = [80, 12, 100, 5, 21, 117];
document.getElementById("demo")[removed] = points;
function myFunction1() {
points.sort();
document.getElementById("demo")[removed] = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo")[removed] = points;
}
</script>
Copy code

Output:

Sort Alphabetically: 100,117,12,21,5,80
Sort Numerically: 5,12,21,80,100,117
15+ JavaScript Array Methods with Examples
How to Use JavaScript Array Filter

Sort an Array of Objects in JavaScript

Arrays in JavaScript are often made up of objects.

Example:


 
const students = [
{type: "John", year:2000},
{type: "Alena", year:1997},
{type: "Niah", year:1999}
]
Copy code

The sort() methods can be utilized to sort the array, even if objects have properties of distinct data types.  

In order to analyze the values of the properties, write a compare function:

Syntax:


 
students.sort(function(a, b){return a.year - b.year});
Copy code

Example:


 
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Array Sort</h2>
<p>Click the buttons to sort students objects on the type.</p>
<button onclick="myFunction()">Sort</button>
<p id="demo"></p>
<script>
const students = [
{type: "John", year:2000},
{type: "Alena", year:1997},
{type: "Niah", year:1999}
];
display();Students
function myFunction() {
students.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});
displayStudents();
}
function displayStudents() {
document.getElementById("demo")[removed] =
cars[0].type + " " + students[0].year + "<br>" +
cars[1].type + " " + students[1].year + "<br>" +
cars[2].type + " " + students[2].year;
}
</script>
</body>
</html>
Copy code

Output:

John 2000
Alena 1997
Niah 1999

Wrapping It Up!

With JavaScript array sort, you can arrange your array elements in a specific way. In the above blog, we have covered JavaScript array sort, compare function, and working of compare function. Additionally, readers can find information on how to find the highest and lowest array objects and JavaScript sort objects.

Explore more- Top JavaScript interview questions and answers

Top JavaScript Array Sort FAQs

What does the sort() method do in JavaScript?

The

sort()
Copy code
method sorts the elements of an array in place, typically in ascending (alphabetical) order, and returns the sorted array.

How does the default sorting work in JavaScript?

By default, sort() converts elements to strings and compares their UTF-16 character sequences. This means numbers are sorted based on their first digit, not their numerical value.

How can you sort an array numerically in JavaScript?

To sort numerically, provide a compare function: array.sort((a, b) => a - b) for ascending order, and array.sort((a, b) => b - a) for descending order.

Can sort() be used for arrays of objects?

Yes, by providing a compare function that specifies the object property to sort by, for example: array.sort((a, b) => a.age - b.age).

About the Author
author-image
Chanchal Aggarwal
Senior Executive Content

Chanchal is a creative and enthusiastic content creator who enjoys writing research-driven, audience-specific and engaging content. Her curiosity for learning and exploring makes her a suitable writer for a variety ... Read Full Bio