How To Sort An Array In JavaScript

In the JavaScript programming language, we are provided the sort() method to sort the data of an array, but it's also used to sort anything other than an array itself; and this JavaScript tutorial shows you some popular methods to sort the data in JavaScript.


Sampled by © JavaScriptBank.com

In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.

Sort() in JavaScript

By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let’s consider the following example of Sort method.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]

The above look fine when sorting an array of string but when it comes to number we will face a little problem.

var list =[ 39, 108, 21, 55, 18, 9]
list.sort() //[108, 18, 21, 39, 55, 9]

Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn’t force you to follow lexicographic order. You may also define a function to sort them in your own way.

Reverse Sort()

We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]
list.reverse() //["Monkey", "Zebra", "Donkey"]

Simple and powerful.

Customize Sort

The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,

  • returns a value less than 0: parameter ‘a’ value is less than parameter ‘b’ value. ‘a’ come BEFORE ‘b’.
  • returns a value greater than 0: parameter ‘a’ value is more than parameter ‘b’ value. ‘a’ come AFTER ‘b’
  • returns exactly 0: parameter ‘a’ and ‘b’ have the same value. no change.

With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.

function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the ‘?’ symbol and we will get a shorter version of the code above.

function sortmyway(data_A, data_B)
{
return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0));
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

We can even shorten the above declaration to perform the same task as shown below,

function sortmyway(data_A, data_B)
{
	return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

All the methods above sort the array in ascending order.

Sort Descending order

Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,


function sortmyway(data_A, data_B)
{
	return (data_B - data_A);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]

You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.

Random Sort Array

Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.

function sortmyway(data_A, data_B)
{
	return 0.5 - Math.random(); //random gives us result between 0 and 1
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]

Summary

Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!

You can find more JavaScript codes for sorting an Array at here: Algorithms by JavaScript

Language
Translate this page to English Translate this page to French Translate this page to Vietnamese

Recent articles
How to open a car sharing service
Vue developer as a vital part of every software team
Vue.js developers: hire them, use them and get ahead of the competition
3 Reasons Why Java is so Popular
Migrate to Angular: why and how you should do it
The Possible Working Methods of Python Ideology
JavaScript Research Paper: 6 Writing Tips to Craft a Masterpiece
Learning How to Make Use of New Marketing Trends
5 Important Elements of an E-commerce Website
How To Create A Successful Prototype For Your PCB


Top view articles
Top 10 Beautiful Christmas Countdown Timers
Adding JavaScript to WordPress Effectively with JavaScript Localization feature
65 Free JavaScript Photo Gallery Solutions
16 Free Code Syntax Highlighters by Javascript For Better Programming
Best Free Linux Web Programming Editors
Top 10 Best JavaScript eBooks that Beginners should Learn
Top 50 Most Addictive and Popular Facebook mini games
More 30 Excellent JavaScript/AJAX based Photo Galleries to Boost your Sites
Top 10 Free Web Chat box Plug-ins and Add-ons
The Ultimate JavaScript Tutorial in Web Design


Free JavaScript Tutorials & Articles
at www.JavaScriptBank.com