Table of contents
1.
Introduction
2.
Sorting Array of Strings
3.
Syntax
4.
Parameters
5.
Return Value
6.
Example
7.
Sorting a Numeric Array in JS
7.1.
Ascending Order
7.2.
Descending Order
8.
Sort Array of Strings in Reverse Order
9.
Sorting Array of Objects
10.
Sort Stability
11.
The Compare Function
11.1.
Sorting an Array in Random Order
11.1.1.
Example:
11.2.
The Fisher-Yates Method
11.2.1.
Example:
11.3.
Find the Lowest (or Highest) Array Value
11.3.1.
Find Min or Max with sort()
11.4.
JavaScript Array Minimum Method
11.4.1.
Using Math.min() on an Array
11.5.
JavaScript Array Maximum Method
11.5.1.
Using Math.max() on an Array
12.
Sorting Object Arrays Stably
13.
Frequently Asked Questions
13.1.
What does sort() do in JavaScript? 
13.2.
How does the compare function work?
13.3.
Can sort() be used for objects? 
14.
Conclusion
Last Updated: Dec 22, 2024
Easy

JavaScript Array Sort

Author Pallavi singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript arrays are used to store & manipulate lists of data. One common task is sorting the elements in an array into a specific order, like alphabetical or numerical. JavaScript provides several ways to sort arrays, from the built-in sort() method to custom sorting functions. 

JavaScript Array Sort

In this article, we'll discuss different techniques for sorting arrays in JavaScript, like sorting numbers, strings, and objects. 

Sorting Array of Strings

Sorting an array of strings in JavaScript is straightforward, thanks to the sort() method. It arranges the elements in alphabetical order by default.

Syntax

array.sort([compareFunction])

Parameters

  • compareFunction (optional): A function that defines the sort order.

Return Value

The sort() method sorts the array in place and returns the sorted array.

Example

const fruits = ["banana", "apple", "cherry", "date"];
fruits.sort();
console.log(fruits);
You can also try this code with Online Javascript Compiler
Run Code


Output

["apple", "banana", "cherry", "date"]

Sorting a Numeric Array in JS

Sorting numeric arrays requires a compare function to avoid incorrect results due to default string sorting.

Ascending Order

const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[1, 2, 3, 4, 5]

 

Explanation: The compare function subtracts b from a to sort in ascending order.

Descending Order

numbers.sort((a, b) => b - a);
console.log(numbers);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[5, 4, 3, 2, 1]

Sort Array of Strings in Reverse Order

To sort strings in reverse alphabetical order, you can combine the sort() method with the reverse() method.

Example:

const fruits = ["banana", "apple", "cherry", "date"];
fruits.sort().reverse();
console.log(fruits);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

["date", "cherry", "banana", "apple"]

Sorting Array of Objects

Sorting an array of objects often requires custom logic using a compare function.

Example:

const students = [
  { name: "John", age: 22 },
  { name: "Alice", age: 19 },
  { name: "Bob", age: 21 }
];
students.sort((a, b) => a.age - b.age);
console.log(students);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[
  { name: "Alice", age: 19 },
  { name: "Bob", age: 21 },
  { name: "John", age: 22 }
]


Explanation: Objects are sorted based on their age property.

Sort Stability

Sort stability ensures that equal elements retain their original order. JavaScript’s sort() is stable as of ECMAScript 2019.

Example:

const items = [
  { name: "item1", value: 10 },
  { name: "item2", value: 5 },
  { name: "item3", value: 10 }
];
items.sort((a, b) => a.value - b.value);
console.log(items);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[
  { name: "item2", value: 5 },
  { name: "item1", value: 10 },
  { name: "item3", value: 10 }
]

The Compare Function

The compare function defines how two elements are compared. It takes two arguments and returns:

  • A negative value if a should come before b.
     
  • Zero if a and b are equal.
     
  • A positive value if a should come after b.
     

Example:

const numbers = [40, 100, 1, 5, 25, 10];
numbers.sort((a, b) => a - b);
console.log(numbers);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[1, 5, 10, 25, 40, 100]

Sorting an Array in Random Order

Randomizing an array can be achieved using a custom compare function.

Example:

const numbers = [1, 2, 3, 4, 5];
numbers.sort(() => Math.random() - 0.5);
console.log(numbers);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: (Randomized)

[4, 1, 5, 2, 3]

The Fisher-Yates Method

The Fisher-Yates method, also known as the Knuth shuffle, is a classic algorithm for shuffling the elements of an array into a random order. It works by starting at the end of the array & swapping each element with a randomly selected element that comes before it.

Example:

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
const numbers = [1, 2, 3, 4, 5];
console.log(shuffle(numbers));
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

[ 4, 2, 3, 1, 5 ]
You can also try this code with Online Javascript Compiler
Run Code

In this code, we start with a for loop that iterates from the last index of the array (`array.length - 1`) down to the second element. In each iteration, we generate a random index `j` between 0 and the current index `i` (inclusive) using `Math.random()`. Then, we swap the elements at indices `i` and `j` using array destructuring. After the loop completes, the array is shuffled in place & returned.

The Fisher-Yates method has a time complexity of O(n), where n is the length of the array, making it an efficient way to shuffle elements randomly.

Find the Lowest (or Highest) Array Value

 JavaScript provides built-in methods to accomplish this easily. To find the lowest value in an array, you can use the `Math.min()` method along with the spread operator (`...`): . Similarly, to find the highest value in an array, you can use the `Math.max()` method with the spread operator:.

Find Min or Max with sort()

const numbers = [10, 5, 20, 8, 30];
const min = numbers.sort((a, b) => a - b)[0];
const max = numbers.sort((a, b) => b - a)[0];
console.log(`Min: ${min}, Max: ${max}`);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Min: 5, Max: 30

JavaScript Array Minimum Method

There is no direct min() method for arrays in JavaScript, but you can use Math.min() with the spread operator as shown above.

Using Math.min() on an Array

const numbers = [10, 5, 20, 8, 30];
const min = Math.min(...numbers);
console.log(min);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

5

JavaScript Array Maximum Method

Similarly, use Math.max() with the spread operator for finding the maximum value.

Using Math.max() on an Array

const numbers = [10, 5, 20, 8, 30];
const max = Math.max(...numbers);
console.log(max);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

30

Sorting Object Arrays Stably

When sorting an array of objects based on a specific property, it's important to consider the stability of the sorting algorithm. A stable sorting algorithm maintains the relative order of equal elements, while an unstable algorithm may change their order. 

JavaScript's built-in `sort()` method uses an unstable sorting algorithm. To perform a stable sort on an array of objects, you can use a custom comparison function.

Example:

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 35 }
];

people.sort((a, b) => {
  if (a.age !== b.age) {
    return a.age - b.age;
  } else {
    return people.indexOf(a) - people.indexOf(b);
  }
});

console.log(people);
You can also try this code with Online Javascript Compiler
Run Code

 

Output

[ { name: 'Charlie', age: 25 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'David', age: 35 } 
]

 

In this code, we have an array of `people` objects, each with a `name` and an `age` property. To sort the array based on the `age` property while maintaining the original order of objects with the same age, we use a custom comparison function. 

The comparison function takes two objects `a` and `b`. It first checks if the `age` properties are different. If they are, it returns the difference between `a.age` and `b.age`, effectively sorting the objects by age. If the `age` properties are the same, the function uses the `indexOf()` method to compare the original indices of the objects in the array. 

This ensures that the relative order of objects with the same age is preserved. After sorting, the `people` array will be sorted by age, and objects with the same age will maintain their original order.

Frequently Asked Questions

What does sort() do in JavaScript? 

The sort() method organizes array elements either alphabetically or numerically, depending on the provided compare function.

How does the compare function work?

 It takes two arguments and returns a negative, zero, or positive value to determine their order.

Can sort() be used for objects? 

Yes, with a custom compare function, you can sort arrays of objects based on specific properties.

Conclusion

Sorting arrays in JavaScript is a versatile and powerful tool. This article covered sorting strings, numbers, and objects, along with advanced techniques like randomizing and finding minimum/maximum values. Understanding sort() and its compare function is essential for working efficiently with arrays in JavaScript.

Live masterclass