Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
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.
// Array of integers
let intArray = [5, 3, 6, 2, 4, 1];
intArray.sort();
console.log(intArray); // output: [1, 2, 3, 4, 5, 6]intArray containing integers.sort() method on the intArray, the sort() method arranges the elements in an increasing order. As a result, I obtain the output in ascending order: [1, 2, 3, 4, 5, 6].sort() Methodsort() method: anyArray.sort(optionalFunction).sort() method on any array. The sort() method also accepts an optional parameter: optionalFunction.optionalFunction returns the sorted array elements if provided.sort() method is a built-in function that allows us to organize the array elements in a specific order.Here, I will apply the sort() method without passing the function on: Array of strings and an array of numbers.
girlsList.sort() method on array girlsList, 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']girlsList are sorted in ascending order.Jaya comes before Rekha because J comes before R in 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.
numArray and apply the sort() method on numArray.
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']['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'].
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
girlsList with elements ["Rekha", "Jaya", "Sushama"].sort() method to this array, the order was changed to ["Jaya", "Rekha", "Sushama"].girlsList array were in uppercase.newGirlsList = ["rekha", "Jaya", "sushama", "Suhaani"].newGirlsList array have a combination of uppercase and lowercase letters.let newGirlsList = ["rekha", "Jaya", "sushama", "Suhaani"]
console.log(newGirlsList.sort())sort() method to the newGirlsList array, the resulting order is ["Jaya", "Suhaani", "rekha", "sushama"].newGirlsList does 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 newGirlsList with four elements: "rekha", "Jaya", "sushama", "Suhaani". I want to arrange these elements in alphabetical order.
To achieve this, I define a function called compareStrings. The compareStrings function accept to parameters: prevIndex and nextIndex.
Inside the compareStrings function, 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 prevIndex will come before nextIndex. If the result is positive, it means nextIndex will come before prevIndex. And if the result is zero, it means the order of prevIndex and nextIndex will remain unchanged.
The final output will be ["Jaya", "rekha", "sushama", "Suhaani"].
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]sort() method sorts array elements in ascending order.sort() method arranges array elements based on a specific characteristic, such as their values, alphabetic order, or UTF-16 representation.sort() method modifies the original array directly, without creating a new array.anyArray.sort(optionalFunction).sort() method on arrays of strings and numbers without passing a function to sort() method. But the results may differ from your desired results.sort() method to achieve the desired sorting order for both strings and numbers.