JavaScript Array toSorted

Summary: in this tutorial, you will learn how to use the JavaScript Array toSorted() method to return a new array with elements sorted.

Introduction to the JavaScript Array toSorted method

The Array.prototype has the sort() method that sorts elements in an array. However, it modifies the original array.

Sometimes, you don’t want to change the original array but create a new one with the elements sorted. In this case, you can use the Array.prototype.toSorted() method.

Here’s the basic syntax of the toSorted() method:

array.toSorted(compareFn);Code language: JavaScript (javascript)

In this syntax:

  • array: This is the array on which you call the method.
  • compareFn (Optional): This is a function that defines the sort order. If you omit it, the toSorted() method will convert the array elements to strings and then sort them according to their character’s Unicode code point values.

The compareFn function accepts two arguments a and b which are the first and second elements for comparison.

The compareFn is expected to return a negative number if a should be sorted before b, a positive number if b should be sorted before a, and zero if the order of a and b does not matter.

The toSorted() function returns a new array with elements sorted in ascending order.

The toSorted() method is generic, meaning that you can call it on a non-array object that has the length property and integer-keyed properties.

In this case, the toSorted() method does the following:

  • First, read the length property of the object.
  • Second, collect all existing integer-keyed properties in the range of 0 to length - 1.
  • Third, sort the elements.
  • Finally, write the elements into a new array.

JavaScript Array toSorted method examples

Let’s explore some examples of using the JavaScript Array toSorted() method.

1) Using the toSorted() method to return a new sorted array of strings

The following example uses the toSorted() method to sort an array of strings:

const colors = ['red','green','blue'];
const sortedColors = colors.toSorted();

console.log(colors);
console.log(sortedColors);Code language: JavaScript (javascript)

Output:

['red', 'green', 'blue']
['blue', 'green', 'red']Code language: JavaScript (javascript)

The output indicates that the original array (colors) does not change but the resulting array (sortedColors ) has elements sorted.

2) Using the toSorted() method to return a new sorted array of numbers

The following example uses the toSorted() method to sort an array of numbers:

const scores = [3, 1, 2, 7, 9];
const sortedScores = scores.toSorted((a,b) => a - b);

console.log(scores);
console.log(sortedScores);Code language: JavaScript (javascript)

Output:

[3, 1, 2, 7, 9]
[1, 2, 3, 7, 9]Code language: JavaScript (javascript)

In this example, we use the compareFn parameter that compares two numbers to sort the elements of the scores array numerically in ascending order.

To sort the numbers in descending order, you change the compareFn parameter as follows:

const scores = [3, 1, 2, 7, 9];
const sortedScores = scores.toSorted((a,b) => b - a);

console.log(scores);
console.log(sortedScores);Code language: JavaScript (javascript)

Output:

[3, 1, 2, 7, 9]
[9, 7, 3, 2, 1]Code language: JavaScript (javascript)

In the compareFn function, we use b - a to instruct the function that if b is greater than a, it returns a positive value, leading to b being sorted before a.

As a result, the toSorted() method sorts the array in descending order because it places the larger numbers (higher values of b) before smaller numbers (lower values of a).

3) Using the toSorted() method to sort an array of objects by a property

The following example uses the toSorted() method to sort an array of books by publication year without modifying the original array:

// Original array of books
const books = [
  { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925 },
  { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 },
  { title: '1984', author: 'George Orwell', year: 1949 },
  { title: 'Brave New World', author: 'Aldous Huxley', year: 1932 }
];

// Creating a sorted copy based on the publication year using toSorted()
const sortedBooks = books.toSorted((a, b) => a.year - b.year);

// Output the sorted copy and the original array
console.log(sortedBooks);Code language: JavaScript (javascript)

Output:

[
  { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald', year: 1925},
  { title: 'Brave New World', author: 'Aldous Huxley', year: 1932 },
  { title: '1984', author: 'George Orwell', year: 1949 },
  { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }
]Code language: JavaScript (javascript)

4) Calling toSorted() method on non-array objects

The following example illustrates how to call the toSorted() method on an object that has the length property and integer-keyed properties:

const arrayLike = {
  length: 3,
  unrelated: "foo",
  0: 5,
  2: 4,
  3: 3, // ignored by toSorted() since length is 3
};
console.log(Array.prototype.toSorted.call(arrayLike));
// [4, 5, undefined]Code language: JavaScript (javascript)

5) Using toSorted() on sparse arrays

The following example calls the toSorted() method on a sparse array. The toSorted() method treats the empty slots as if they have the value undefined:

const skills = ['JS',,'Node.js'];
const sortedSkills = skills.toSorted();

console.log(sortedSkills);Code language: JavaScript (javascript)

Output:

['JS', 'Node.js', undefined]Code language: JavaScript (javascript)

Summary

  • Use the JavaScript Array toSorted() method to return a new array whose elements are sorted without modifying the original array.
  • The toSorted() method is generic so that you can call it on a non-array object that has the length property and integer-keyed properties.
  • When applying the toSorted() method to sparse arrays, it iterates through empty slots, treating them as if they contain the value undefined.
Was this tutorial helpful ?