Array Sort In JavaScript : Everything About Sorting Arrays In JavaScript

Last updated on Mar 13,2023 1.9K Views

Array Sort In JavaScript : Everything About Sorting Arrays In JavaScript

edureka.co

Sorting lets you arrange data in a required form. Meaning, it becomes easier to access and process this data. In this article on ‘Array Sort In JavaScript’ we would be exploring different ways of sorting data in JavaScript. We will be focusing on following pointers,

So let us get started with the first topic of this Array Sort In JavaScript Article

Array Sort In JavaScript Article

Sort Method In JavaScript

The sort() method sorts the elements present in the array accordingly and returns the sorted array as an output to the user. The built-in method converts each element present in the array into a string , and compares them in Unicode code point order.Though start with installation first.

The code below follows the most basic array sort:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">  
</head>
<body>
<script>
var music = ["Pop", "Rock", "Jazz", "Blues", "Metal"];
var sorted = music.sort();
document.write(music + "<br>");  
</script>
</body>
</html>
   

Output:

Blues,Jazz,Metal,Pop,Rock

Now let us continue with ‘Array Sort In JavaScript’ and see how can we sort numerical values,

Sorting Numerical Values

Sorting numbers as strings produces false and incorrect results.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">  
</head>
<body>
<script>
var music = ["Pop", "Rock", "Jazz", "Blues", "Metal"];
var sorted = music.sort();
document.write(music + "<br>");  
</script>
</body>
</html>
                            

Output:

10,100,34,45,69,87

The result seems to be absolutely inaccurate. This happens because the numeric array gets converted to a string by the sort() method. The problem can be eradicated by using a compare function.

The syntax for the function is as follows:

array.sort([compareFunction])

The compare function sorts the elements present in the array based on different attributes and in a different order. The sort() function compares two values and sends the values to the compare function. The compare function follows the test cases given below:

In this bit of Array Sort in JavaScript we will sort data in ascending order,

Sorting Array In Ascending Order

The following example demonstrates the procedure of sorting the array in an ascending order.

<!DOCTYPE html>
<html>
<body>
<script>
var num = [45, 34, 69, 87, 100, 10];
num.sort(); // Sorts numbers array
document.write(num);
</script>
</body>
</html>                            

Output:

3,18,25,28,29,69

Moving further let us checkout how to sort arrays in descending order

Sorting Array In Descending Order

The array can be sorted in a descending order in the following way:

<!DOCTYPE html>
<html>
<body>
<script>
var num = [3, 25, 18, 28, 69, 29];
//Sorting an array using compare function
num.sort(function(a, b) {
return a - b;
});
document.write(num);
</script>
</body>
</html> 

Output:

69,29,28,25,18,3

We can even sort arrays of objects, let us see how to do that,

Sorting Array Of Objects

The compare function can be used to sort object arrays in an efficient manner.

<!DOCTYPE html>
<html>
<body>
<script>
var people = [
{ name: "Jeremy"},
{ name: "Ari" },
{ name: "Jonathan"},
{ name: "Alec"},
{ name: "Stephen"}
];
//Sort by name
people.sort(function(a, b) {
var x = a.name.toLowerCase(); // ignore upper and lowercase
var y = b.name.toLowerCase(); // ignore upper and lowercase
if(x < y) {
return -1;
}
if(x > y) {
return 1;
}
//names should be equal
return 0;
});    
//Loop through all the elements in the array 
for(var i in people)  {  
//Loop through all the properties in the object  
for(var prop in people[i]) {  
document.write(prop + ": " + people[i][prop] + "<br>"); 
}
document.write("<hr>");
}

Output:

name: Alec

name: Ari

name: Jeremy

name: Jonathan

name: Stephen

The methods explained in the article meticulously demonstrate the fact that the sort function linked with the compare function plays a crucial part in the scripting language. To learn more, join the Full Stack Developer Certification Training today.

With this we come to the end of this blog on ‘Array Sort In JavaScript’. I hope you found this informative and helpful, stay tuned for more tutorials on similar topics.You may also checkout our training program to get in-depth knowledge on jQuery along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of  this blog and we will get back to you.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 7th December,2024

7th December

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES