Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

JavaScript Array Sort() Method

Last Updated on June 8, 2023 by Mayank Dham

You may arrange array elements in a sequential sequence using the Array sort() method. In addition to returning the sorted array, the Array sort() method changes the positions of the items in the starting array.

The array items are ordinarily sorted using the sort() function in ascending order, with the smallest value coming before the biggest.

In order to establish the ordering, the Array sort() function converts items to strings and compares the strings.

Consider the following example:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort();
console.log(numbers);

Output:

[ 0, 1, 10, 2, 20, 3, 30 ]

In this case, the string "10" occurs before "2" while comparing strings, therefore the sort() function inserts "10" before "2".

You must supply a comparison function to the sort() method in order to correct this. The comparative function will be used by the Array sort() method to determine the elemental ordering.

Syntax of the Array sort() function

array.sort(comparefunction)

A function that compares two array elements is an optional parameter to the Array sort() method.

If the comparison function is not used, the Array sort() method sorts the elements according to the previously given Unicode code point values.

The Array sort() method’s comparison function takes two inputs and produces a result that indicates the sort order. The comparison function’s syntax is demonstrated by the following:

function compare(a,b) {
  // ...
}

Two inputs, a and b, are accepted by the compare() method. The compare() function’s return value is used by the sort() method to order the items according to the following guidelines:

  • The sort() function orders a lower in the index than b if compare(a,b) is less than zero. Meaning that a will come first.
  • The sort() function sorts b to a lower index than a, meaning b will come first, if compare(a,b) is higher than zero.
  • The sort() function assumes that a and b are equal and maintains their current places if compare(a,b) returns zero.

You may use the following syntax to resolve the number sorting problem:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort( function( a , b){
    if(a > b) return 1;
    if(a  {
    if(a > b) return 1;
    if(a  a - b);
console.log(numbers);

Sorting an Array of Strings

Let’s say you have an array of strings called animals that looks like this:

let animals = [
    'cat', 'dog', 'elephant', 'bee', 'ant'
];

The following example demonstrates how to use the Array sort() method without specifying the comparison function to alphabetically organize the animals array’s items in ascending order:

let animals = [
    'cat', 'dog', 'elephant', 'bee', 'ant'
];
animals.sort();
console.log(animals);

Output:

[ 'ant', 'bee', 'cat', 'dog', 'elephant' ]

You must modify the comparison function’s logic and feed it to the sort() method as shown in the example below in order to sort the animal’s array in descending order.

    let animals = [
    'cat', 'dog', 'elephant', 'bee', 'ant'
    ];

animals.sort((a, b) => {
    if (a > b)
        return -1;
    if (a  y ? 1 : -1;

});

Output:

[ 'ant', 'bee', 'Cat', 'dog', 'Elephant' ]

Sorting an Array of Strings with Non-ASCII Characters

With strings containing ASCII characters, the sort() method functions as intended. However, the sort() method will not function properly for strings that contain non-ASCII characters, such as é, è, etc. For instance:

let animaux = ['zèbre', 'abeille', 'écureuil', 'chat'];
animaux.sort();

console.log(animaux);

The écureuil string, as you can see, ought to come before the zèbre string.

To fix this, compare strings in a certain locale using the localeCompare() function of the String object, like in the following example:

animaux.sort(function (a, b) {
    return a.localeCompare(b);
});
console.log(animaux);

Output:

[ 'abeille', 'chat', 'écureuill', 'zèbree' ]

The elements of the animaux array now are in the correct order.

Sorting an Array of Numbers

Assume you have a collection of scores, like in the example below.

let scores = [
    9, 80, 10, 20, 5, 70
];

You must input a custom comparison function that compares two numbers into an array of numbers in order to numerically sort them.
The scores array is numerically sorted in ascending order in the example that follows.

let scores = [
    9, 80, 10, 20, 5, 70
];
// sort numbers in ascending order
scores.sort((a, b) => a - b);

console.log(scores);

Output:

[ 5, 9, 10, 20, 70, 80 ]

You just need to use the compare function’s logic in the other direction, as seen in the example below, to numerically arrange an array of integers in descending order:

let scores = [
    9, 80, 10, 20, 5, 70
];
// descending order
scores.sort((a, b) => b - a);
console.log(scores);

Output:

[80, 70, 20, 10, 9, 5]

Sorting an Array of Objects by a Specified Property

An array of employee objects is shown below. Each object has the three values name, salary, and hireDate.

let employees = [
    {name: 'John', salary: 90000, hireDate: "July 1, 2010"},
    {name: 'David', salary: 75000, hireDate: "August 15, 2009"},
    {name: 'Ana', salary: 80000, hireDate: "December 12, 2011"}
];

Sorting Objects by a Numeric Property

The method for sorting the employees’ salaries in ascending order is demonstrated in the example below.

// sort by salary
employees.sort(function (x, y) {
    return x.salary - y.salary;
});

console.table(employees);

This illustration is comparable to the illustration of sorting an array of integers upwards. The distinction is because it contrasts two items salaries as opposed to other properties.

Sorting Objects by a String Property

You supply the compare function, which compares two strings case-insensitively, the following information in order to case-insensitively arrange the workers array by name property:

employees.sort(function (x, y) {
    let a = x.name.toUpperCase(),
        b = y.name.toUpperCase();
    return a == b ? 0 : a > b ? 1 : -1;
});

console.table(employees);

Sorting Objects by the Date Property

Lets say you want to organise the workers by the date they were hired.

The hireDate property of the employee object contains the hiring date information. However, it isn’t the Date object; rather, it’s only a string that symbolises a legitimate date.

Therefore, in order to compare two dates, which is equivalent to comparing two integers, you must first generate a valid Date object from the date string.
The answer is as follows:

employees.sort(function (x, y) {
    let a = new Date(x.hireDate),
        b = new Date(y.hireDate);
    return a - b;
});

console.table(employees);

Optimising JavaScript Array sort() Method

In actuality, the comparison function is used many times by the sort() method for each entry in the array.
See the example below:

let rivers = ['Nile', 'Amazon', 'Congo', 'Mississippi', 'Rio-Grande'];

rivers.sort(function (a, b) {
    console.log(a, b);
    return a.length - b.length;
});

Output:

Amazon Nile
Congo Amazon
Congo Amazon
Congo Nile
Mississippi Congo
Mississippi Amazon
Rio-Grande Amazon
Rio-Grande Mississippi

How it works:

  • Declare a list of rivers first, including just the well-known river names.
  • Second, use the sort() function to order the river array according to the length of each entry. Every time the sort() method uses the comparison function, we report the contents of the rivers array to the browser console.
  • Each element has been assessed more than once, as seen in the result above, for example, Amazon has been reviewed four times and Congo twice.
  • Performance might be affected by an increase in the number of array elements.
  • The number of times the comparison function is used cannot be decreased. You may, however, lessen the amount of effort the comparison needs to perform. This process is known as the Schwartzian Transform.

To implement this, you follow these steps:

  1. Use the map() function to first extract the real values into a temporary array.
  2. Next, order the temporary array by already-evaluated items (or transformed).
  3. Third, navigate the informal array to obtain an array containing the proper ad hoc.

Here is the solution:

// temporary array holds objects with position
// and length of element
var lengths = rivers.map(function (e, i) {
    return {index: i, value: e.length };
});

// sorting the lengths array containing the lengths of
// river names
lengths.sort(function (a, b) {
    return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// copy element back to the array
var sortedRivers = lengths.map(function (e) {
    return rivers[e.index];
});

console.log(sortedRivers);

Output:

[ 'Nile', 'Congo', 'Amazon', 'Rio-Grande', 'Mississippi' ]

Conclusion
The JavaScript Array..sort() method is a powerful tool for sorting the elements of an array. It provides flexibility and customization options for sorting arrays of different data types. The method sorts the elements in place and returns the sorted array. It uses a stable sorting algorithm, typically a variant of quicksort or mergesort, to efficiently sort the array.

Frequently Asked Questions (FAQs):

Q1: How does the sort() method work in JavaScript?
The sort() method in JavaScript converts the elements of the array into strings and then compares them based on their Unicode code points. By default, the elements are sorted in ascending order. The method modifies the original array and returns the sorted array.

Q2: Can I use the sort() method to sort arrays of different data types?
Yes, the sort() method can sort arrays containing elements of different data types. However, the sorting order may not always be intuitive. For example, if you have an array of numbers and strings, the numbers will be converted to strings and sorted based on their Unicode code points.

Q3: How can I customize the sorting order using the sort() method?
The sort() method accepts an optional compare function that can be used to define a custom sorting order. The compare function takes two parameters (a and b) representing two elements being compared. It should return a negative value if a should be placed before b, a positive value if a should be placed after b, and 0 if both elements are equal in terms of sorting.

Q4: Can the sort() method handle the sorting of complex objects?
Yes, the sort() method can sort arrays of complex objects. By providing a compare function that specifies the sorting criteria based on specific object properties, you can customize the sorting order for complex objects. For example, you can sort an array of objects based on their name or age properties.

Q5: What is the time complexity of the sort() method?
The time complexity of the sort() method depends on the sorting algorithm used by the JavaScript engine. In most modern engines, the average time complexity is O(n log n), where n is the number of elements in the array. However, it’s important to note that the worst-case time complexity can be O(n^2) for some sorting algorithms, depending on the data and the compare function used.

Q6: Does the sort() method modify the original array?
Yes, the sort() method modifies the original array in place. It rearranges the elements of the array according to the sorting order and returns the sorted array. If you want to preserve the original array, you should create a copy of it before applying the sort() method.

Leave a Reply

Your email address will not be published. Required fields are marked *