Skip to main content

Sort an array JavaScript

JavaScript provides several methods to sort arrays.

In this tutorial, you will learn about JavaScript Sorting Arrays using our interactive Code Editor.

Let's dive in 🏊

Sorting an Array

  • sort(): This method sorts the elements of an array in place and returns the sorted array. By default, it sorts the array in ascending order.

Example:

const fruits = ["apple", "banana", "cherry", "date"];
fruits.sort();
console.log(fruits); // Output: ['apple', 'banana', 'cherry', 'date']

To sort the array in descending order, you can provide a compare function as follows:

const numbers = [4, 2, 1, 3];
numbers.sort((a, b) => b - a);
console.log(numbers); // Output: [4, 3, 2, 1]

Reversing an Array

  • reverse(): This method reverses the order of the elements in an array in place.

Example:

const numbers = [1, 2, 3, 4];
numbers.reverse();
console.log(numbers); // Output: [4, 3, 2, 1]

Concating an Array

  • concat(): This method joins two or more arrays and returns a new array.

Example:

const fruits1 = ["apple", "banana"];
const fruits2 = ["cherry", "date"];
const fruits3 = ["elderberry"];
const allFruits = fruits1.concat(fruits2, fruits3);
console.log(allFruits); // Output: ['apple', 'banana', 'cherry', 'date', 'elderberry']
info

concat() does not sort the resulting array.

Slicing an Array

  • slice(): This method returns a portion of an array as a new array.

Example:

const numbers = [1, 2, 3, 4];
const slicedNumbers = numbers.slice(1, 3);
console.log(slicedNumbers); // Output: [2, 3]
info

slice() does not sort the resulting array.

indexOf() an Array

  • indexOf(): This method returns the index of the first occurrence of a specified element in an array. If the element is not found, it returns -1.

Example:

const fruits = ["apple", "banana", "cherry", "date"];
const index = fruits.indexOf("banana");
console.log(index); // Output: 1

lastIndexOf() of an Array

  • lastIndexOf(): This method returns the index of the last occurrence of a specified element in an array. If the element is not found, it returns -1.

Example:

const fruits = ["apple", "banana", "cherry", "date", "banana"];
const index = fruits.lastIndexOf("banana");
console.log(index); // Output: 4

Sorting an Array in Random Order

To sort an array in a random order, you can use the sort() method with a compare function that returns a random value of -1, 0, or 1.

This will cause the elements of the array to be rearranged in a random order.

Example:

const numbers = [1, 2, 3, 4, 5];
numbers.sort(() => Math.random() - 0.5);
console.log(numbers); // Output: [4, 1, 2, 5, 3]

In this example:

  • The compare function returns a random value between -0.5 and 0.5 for each pair of elements being compared.
  • This causes the sort() method to rearrange the elements of the array in a random order.
note

Note that randomly sorting an array using the method described may not produce a perfectly uniform distribution of permutations. For a more rigorous and uniform way of shuffling an array, consider using a library like Lodash, which offers a shuffle() method.

Using Math.max() on an Array

The Math.max() method is used to find the maximum value of a set of numbers. However, it cannot be used directly on an array.

To find the maximum value of an array, you need to use the apply() method to pass the array as the this value, and as an argument to the Math.max() method.

Example:

const numbers = [10, 5, 8, 3, 9];
const maxNumber = Math.max.apply(null, numbers);
console.log(maxNumber); // Output: 10

In this example:

  • The apply() method is used to call the Math.max() method with the this value set to null (since Math.max() does not use this), and the numbers array as the arguments.
  • This causes the Math.max() method to return the maximum value of the array.

Alternatively, in ES6 you can use the spread operator to pass the array as separate arguments to the Math.max() method:

const numbers = [10, 5, 8, 3, 9];
const maxNumber = Math.max(...numbers);
console.log(maxNumber); // Output: 10

This achieves the same result as using apply() with the spread operator ... to pass the array as arguments to the Math.max() method.

Using Math.min() on an Array

Similar to Math.max(), the Math.min() method is used to find the minimum value of a set of numbers, and cannot be used directly on an array. To find the minimum value of an array, you can use the apply() method to pass the array as the this value, and as an argument to the Math.min() method.

As an example:

const numbers = [10, 5, 8, 3, 9];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); // Output: 3

In this example:

  • The apply() method is used to call the Math.min() method with the this value set to null (since Math.min() does not use this), and the numbers array as the arguments.
  • This causes the Math.min() method to return the minimum value of the array.

Alternatively, in ES6 you can use the spread operator to pass the array as separate arguments to the Math.min() method:

const numbers = [10, 5, 8, 3, 9];
const minNumber = Math.min(...numbers);
console.log(minNumber); // Output: 3

This achieves the same result as using apply() with the spread operator ... to pass the array as arguments to the Math.min() method.

Sorting Object Arrays

Sorting an array of objects in JavaScript requires defining a compare function that specifies how the objects should be compared.

The sort() method can then be called on the array and passed the compare function as an argument.

Example:

const people = [
{name: "John", age: 35},
{name: "Mary", age: 28},
{name: "Bob", age: 45},
{name: "Alice", age: 30},
];

people.sort((a, b) => a.age - b.age);
console.log(people);
// Output: [{ name: 'Mary', age: 28 }, { name: 'Alice', age: 30 }, { name: 'John', age: 35 }, { name: 'Bob', age: 45 }]

In this example:

  • The people array contains objects with name and age properties. The sort() method is called on the array with a compare function that compares the age property of each object.
  • The function returns a negative value if a should come before b, zero if they are equal, and a positive value if b should come before a.
  • This causes the sort() method to rearrange the objects in the array in ascending order of age.

To sort in descending order, you can simply reverse the order of the comparison:

people.sort((a, b) => b.age - a.age);
console.log(people);
// Output: [{ name: 'Bob', age: 45 }, { name: 'John', age: 35 }, { name: 'Alice', age: 30 }, { name: 'Mary', age: 28 }]

This causes the sort() method to rearrange the objects in the array in descending order of age.