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

The Array sort() function enables you to order array elements sequentially. The Array sort() function modifies the locations of the elements in the initial array in addition to returning the sorted 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
So, with this we came to an end of this article i.e. JavaScript Array Sort() method. We have studied various approaches of Array sort.

Leave a Reply

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