JavaScript Array Sort
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.
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
- What is Sorting in JavaScript Array?
- Compare Function in JavaScript Sort
- How Compare Function Works?
- Finding the Highest or Lowest Array Value
- Sort an Array of Objects in JavaScript
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 orderlet sortedArray = names.sort();console.log(sortedArray)
// 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 orderlet sortedArray = numbers.sort();console.log(sortedArray);
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.
Best-suited Programming courses for you
Learn Programming with these high-rated online courses
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)
To gain better clarity about the compare function, let us understand how it works with the help of an illustration.
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.
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>
Output:
Sort Alphabetically: 100,117,12,21,5,80 Sort Numerically: 5,12,21,80,100,117
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}]
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});
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>
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()
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).
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