JavaScript Array sort() method

The sort method in JavaScript is employed to organize the elements within an array according to a specific sequence. By default, this sort function arranges the elements in ascending order. In JavaScript, the array's sort method implements an in-place algorithm to perform the sorting of an array.

In this article, we will explore the different techniques for sorting arrays that contain numbers, strings, and objects.

Syntax

The syntax for the sort method is illustrated as follows:

Example

array.sort([compareFunction])

Parameter

compareFunction: This parameter is not mandatory. It signifies a function that defines a different sorting sequence. In the absence of this function, elements will be transformed into strings and compared based on their UTF-16 code point values.

Return

It returns an array of sorted elements.

JavaScript Array sort Method Examples

In this section, we will explore the sort method by examining a series of examples.

Example 1: Sorting an array of string elements

Let’s examine a straightforward illustration to arrange an array consisting of string elements.

Example

Example

let arr = ["AngularJS", "Node.js", "jQuery", "Bootstrap"]  

let result = arr.sort();  

console.log(result);

Output:

Output

[ 'AngularJS', 'Bootstrap', 'Node.js', 'jQuery' ]

Clarification: In the preceding example, we declared a variable called arr utilizing let. We initialized it with an array that holds string elements. By employing the sort method of the array, we organized the elements and saved the resulting output in a variable referred to as result.

Example 2: An example of sorting an array of numbers

Let’s examine a basic example that demonstrates how to arrange an array consisting of numerical elements in a sorted order.

Example

Example

let arr = [2, 4, 1, 8, 5];  

let result = arr.sort();  

console.log(result);

Output:

Output

[1, 2, 4, 5, 8]

Explanation:

In the preceding example, we established a variable called arr utilizing the let keyword. We assigned it an array composed of numeric values. By employing the sort method, we organized the array and saved the resulting output in a variable named result.

Note: The default sort converts numbers to strings so results may be incorrect for multi-digit numbers. Always use a comparison function for numbers.

Example 3: Sorting an array of number elements in ascending order using the compare function

In JavaScript, the compare function tells us how to compare two elements. We pass it two arguments, and it returns:

  • In this function, if a should come before b, then it gives us a negative value.
  • It gives us zero if a and b are equal.
  • A positive value is given by it if a comes after b.

Let’s examine an illustration of how to sort elements in ascending order utilizing the compare function.

Example

Example

let arr = [2, 4, 1, 8, 5];  

let result = arr.sort(function compare(a, b)  

{  

  return a - b;  

}); 

console.log(result);

Output:

Output

[ 1, 2, 4, 5, 8 ]

Explanation:

In the preceding illustration, we created a variable called arr utilizing the let keyword and assigned it to an array that holds a numeric value. The array's elements are organized in ascending order by means of a function, and the resulting output is saved in a variable referred to as result.

Example 4: Sorting an array of number elements in descending order using the compare function

Let's examine an example that demonstrates how to sort elements in descending order utilizing the compare function.

Example

Example

let arr = [2, 4, 1, 8, 5];  

let result = arr.sort(function compare(a, b)  

{  

  return b - a;  

});  

console.log(result);

Output:

Output

[ 8, 5, 4, 2, 1 ]

Explanation:

In the preceding example, we created a variable referred to as arr utilizing the let keyword. By employing a function, we arranged the elements in a descending sequence. The outcome was then stored in a variable called result.

Example 5: Extracting the minimum value from an array using the sort method

Let us examine an example that demonstrates how to retrieve the smallest value from an array.

Example

Example

let arr = [2, 4, 1, 8, 5];  

let result = arr.sort((a, b) => a - b); 

console.log(result[0]);

Output:

Explanation:

In the preceding example, we declared a variable called arr utilizing the let keyword. We assigned to it an array composed of numerical values. By applying the sort method, we arranged the elements of the array in order. Subsequently, we logged the results to the console.

Example 6: Extracting maximum value using the sort method

Let's examine an example that demonstrates how to retrieve the highest value from an array.

Example

Example

let arr = [2, 4, 1, 8, 5];  

let result = arr.sort((a, b) => b - a); 

console.log(result[0]);

Output:

Explanation:

In the preceding example, we declared a variable called arr with the let keyword. We initialized it with several elements. We employed the sort method to organize the elements in order, and we used the reverse method to invert the order of the array's elements.

Example 7: Sorting an array using sort and string.localeCompare Methods

In JavaScript, the string.localeCompare function can be employed within the comparator function to achieve sorting in descending order.

In this illustration, we will explore the process of arranging and reversing an array that is comprised of string elements.

Example

Example

let myArray = ["JavaScript", "C++", "HTML", "ReactJs"];

console.log(myArray);

myArray.sort((x, y) => x.localeCompare(y));

console.log(myArray);

Output:

Output

[ 'JavaScript', 'C++', 'HTML', 'ReactJs' ]

[ 'C++', 'HTML', 'JavaScript', 'ReactJs' ]

Explanation:

In the preceding example, we established a variable referred to as myArray utilizing the let keyword. This variable was assigned an array consisting of string elements. Within the compare function, we utilized localeCompare to organize the strings in alphabetical order while considering locale-specific nuances.

Example 8: Sorting an Array of Objects

In this illustration, we will explore the process of arranging an array of objects in a specific order.

Example

Example

let myArray = [

  {name: "Sameer", age: 28 },

  {name: "Vikash", age: 18 },

  {name: "Ravi", age: 20 },

  {name: "Anish", age: 15 },

  ];

myArray.sort((x,y) => x.age - y.age);

console.log(myArray);

Output:

Output

[

  { name: 'Anish', age: 15 },

  { name: 'Vikash', age: 18 },

  { name: 'Ravi', age: 20 },

  { name: 'Sameer', age: 28 }

]

Explanation:

In the preceding example, we established a variable called myArray and initialized it with an array containing objects. Utilizing the sort method, we arranged the objects according to their age.

Uses of JavaScript Array Sort Method

Below are several applications of the JavaScript Array sort function:

  • Sorting String Alphabetically : In JavaScript, the sort method in the array handles array elements as strings and sorts them in ascending alphabetical order based on their UTF-16 code unit values.
  • Sorting Numbers : When a developer wants to sort the numbers, they need to create a custom compare function. It is necessary to use a compare function because the default sort compares numbers as strings which leads to wrong output. The compare function in JavaScript decides the sort order by giving a negative, zero, or positive value.
  • Sorting Arrays of Objects : In JavaScript, the sort method, with a custom compare function, can sort arrays of objects based on the values of specific properties within those objects. This helps us with complex sorting criteria.
  • Sorting Dates: We can use the array sort method to sort the dates. We have to convert the date to numerical representations, and after that, compare those values within a custom function.
  • Conclusion

In this article, we have explored the sort method for arrays in JavaScript. This topic holds significant importance within the JavaScript programming language. We have examined different techniques for sorting an array, complete with illustrative examples.

In JavaScript, what is the functionality of the array.sort method?

In JavaScript, the sort function changes the elements of an array into strings, subsequently arranging them according to their UTF-16 character code values in a non-decreasing sequence.

  1. Is it possible to utilize the sort method on objects in JavaScript?

Indeed, the sort method is applicable for objects in JavaScript. By providing a custom comparison function, you can arrange arrays of objects according to particular properties.

  1. What is the functioning of the compare function in JavaScript?

In JavaScript, the comparison function accepts two parameters and yields a negative, zero, or positive integer to establish their sequence.

  1. What distinguishes the sort method from the toSorted method in JavaScript?

The sort function is employed by the programmer to rearrange the elements of the array, resulting in modifications to the original array. In contrast, the toSorted function produces a new array that is sorted, leaving the original array unchanged.

Input Required

This code uses input(). Please provide values below: