JavaScript Array Sort: A Comprehensive Guide to Sorting Array Elements
Imagine a long line of many students standing together. Now, let's say I want to organize them based on their height. There are two options: arranging them in descending order from tallest to shortest or in ascending order from shortest to tallest. This process of arranging the individuals in a specific order within the queue is known as sorting.
In this article, I will explore the JavaScript array sort() method. So, let's dive in and discover how I can effectively sort arrays in JavaScript using the Javascript Array sort() method.
Table of Contents
Introduction to Javascript Array sort() Method
// Array of integers
let intArray = [5, 3, 6, 2, 4, 1];
intArray.sort();
// highlight-end
console.log(intArray); // output: [1, 2, 3, 4, 5, 6]- In the above code block, I have an array named
intArraycontaining integers. - When i use the
sort()method on theintArray, thesort()method arranges the elements in an increasing order. As a result, I obtain the output in ascending order:[1, 2, 3, 4, 5, 6].
Syntax for Javascript Array sort() Method
- The syntax for javascript array
sort()method:anyArray.sort(optionalFunction). - I can apply the
sort()method on any array. Thesort()method also accepts an optional parameter:optionalFunction. - The
optionalFunctionreturns the sorted array elements if provided. - Therefore, Javascript Array
sort()method is a built-in function that allows us to organize the array elements in a specific order.
Sorting Array Elements Without Passing a Function
Here, I will apply the sort() method without passing the function on: Array of strings and an array of numbers.
Sorting Array of Strings
- In the following example, I have an array of strings named
girlsList. - When I apply the
sort()method on arraygirlsList, I will get the output:['Jaya', 'Rekha', 'Sushama'].
let girlsList = ["Rekha", "Jaya", "Sushama"]
// Sorting an array of strings
girlsLists.sort()
console.log(girlsList) // output: ['Jay', 'Rekha', 'Sushama']- Here, I can see that the names of girls in an array
girlsListare sorted in ascending order. - For example,
Jayacomes beforeRekhabecauseJcomes beforeRin alphabetical sequences.
Note: If there are elements in the array that include
undefined,null, or a space, thesort()method will place them at the end of the array. Consider the following examples:// An array contains undefined let girlsList = ["Rekha", "Jaya", undefined, "Sushama"]; girlsList.sort(); // output: ['Jaya', 'Rekha', 'Sushama', >undefined]// An array contains null let girlsList = ["Rekha", "Jaya", null, "Sushama"]; girlsList.sort(); // output: ['Jaya', 'Rekha', 'Sushama', null]// An array contains space let girlsList = ["Rekha", , "Jaya", "Sushama"]; girlsList.sort(); // output: ['Jaya', 'Rekha', 'Sushama', empty]
- After observing the outputs of the above examples, I can see that the
sort()method placedundefined,null, and blank space asemptyat the end of the array.
Sorting an Array of Numbers
- In the following example, I have an array of numbers named
numArrayand apply thesort()method onnumArray.
let numArray = [1, 20, 2, 3, 50, 40, 9]
numArray.sort()
// Sorting an array of numbers
console.log(numArray) // output: ['1', '2', '20', '3', '40', '50', '9']- The sorted array for the above example is:
['1', '2', '20', '3', '40', '50', '9'].
Note: Yes! the order of the output array doesn't seems right. Because the
sort()method transforms the numbers of an array into UTF-16 format before sorting them, which impacts the order of the elements. Thesort()method performs two steps when sorting an array of numbers.
- First, it converts the numbers into a specific format known as
UTF-16. For example, the array[1, 20, 2, 3, 50, 40, 9]is converted to["\u0031", "\u0032\u0030", "\u0032", "\u0033", "\u0035\u0030", "\u0034\u0030", "\u0039"].- Next, the
sort()method arranges the numbers in ascending order based on the UTF-16 representations:["\u0031", "\u0032", "\u0032\u0030", "\u0033", "\u0034\u0030", "\u0035\u0030", "\u0039"]. This results in the sorted array:['1', '2', '20', '3', '40', '50', '9'].
Sorting Array Elements by Passing a Function
In the previous section, I applied sort() method on an array of strings and an array of numbers without passing a function. Now, I will discuss how to use sort() method with a function parameter. Let's dive
Sorting an Array of Strings: The Correct way
- Previously, I explained an example using the array
girlsListwith elements["Rekha", "Jaya", "Sushama"]. - After applying the
sort()method to this array, the order was changed to["Jaya", "Rekha", "Sushama"]. - It is important to note that all the elements in the
girlsListarray were in uppercase. - Now, let's consider a new scenario where the array is modified as follows:
newGirlsList = ["rekha", "Jaya", "sushama", "Suhaani"]. - This time, the elements in the
newGirlsListarray have a combination of uppercase and lowercase letters.
let newGirlsList = ["rekha", "Jaya", "sushama", "Suhaani"]
console.log(newGirlsList.sort())- After applying the
sort()method to thenewGirlsListarray, the resulting order is["Jaya", "Suhaani", "rekha", "sushama"]. - However, the resulting order of
newGirlsListdoes not match the desired result["Jaya", "rekha", "sushama", "Suhaani"]. Let's explore the solution.
let newGirlsList = ["rekha", "Jaya", "sushama", "Suhaani"]
function compareStrings(prevIndex, nextIndex) {
let prevIndexLowerCase = prevIndex.toLowerCase();
let nextIndexLowerCase = nextIndex.toLowerCase();
return (prevIndexLowerCase - nextIndexLowerCase)
}
console.log(newGirlsList.sort(compareStrings)) // output: ['rekha', 'Jaya', 'sushama', 'Suhaani']- In the above example, there is an array
newGirlsListwith four elements: "rekha", "Jaya", "sushama", "Suhaani". I want to arrange these elements in alphabetical order. - To achieve this, I define a function called
compareStrings. ThecompareStringsfunction accept to parameters:prevIndexandnextIndex. - Inside the
compareStringsfunction, I convert both elements to lowercase using the toLowerCase() method. - Then, I subtract the lowercase nextIndex from the lowercase prevIndex to determine their order respectively.
- If the result is negative, it means
prevIndexwill come beforenextIndex. If the result is positive, it meansnextIndexwill come beforeprevIndex. And if the result is zero, it means the order ofprevIndexandnextIndexwill remain unchanged. - The final output will be
["Jaya", "rekha", "sushama", "Suhaani"].
Sorting an Array of Numbers Example: The Correct Way
let numArray = [1, 20, 2, 3, 50, 40, 9];
function compareNumbers(prevIndex, nextIndex) {
return (prevIndex - nextIndex)
}
console.log(numArray.sort(compareNumbers)) // output: [1, 2, 3, 9, 20, 40, 50]Conclusion
- Sorting is the process of arranging elements in a specific order within an array.
- By default, the
sort()method sorts array elements in ascending order. - The
sort()method arranges array elements based on a specific characteristic, such as their values, alphabetic order, or UTF-16 representation. - The
sort()method modifies the original array directly, without creating a new array. - The syntax for the sort() method is
anyArray.sort(optionalFunction). - We can apply the
sort()method on arrays of strings and numbers without passing a function tosort()method. But the results may differ from your desired results. - If the array contains elements like undefined, null, or spaces, they are placed at the end of the sorted array.
- It is recommended to pass compare function to the
sort()method to achieve the desired sorting order for both strings and numbers. - By providing the appropriate comparison function, we can achieve the desired sorting order for both strings and numbers.