JavaScript toSorted Function Guide with Examples

javascript tosorted function

This guide shows how toSorted function works in JavaScript with arrays. It covers syntax, rules, and examples for numbers, text, and objects within ES2023 support.

Understand the toSorted Function in JavaScript

The toSorted creates a new array with sorted values. It leaves the original array unchanged.

The syntax looks like this:

array.toSorted(compareFunction)

The compareFunction is optional. It defines how to compare two values. toSorted returns a new array that has the sorted values.

The toSorted makes a new array. It sorts values based on the compare function or the default order. It does not change the original array.

Here is an example:

const numbers = [3, 1, 2];
const sortedNumbers = numbers.toSorted();
console.log(sortedNumbers);

This returns a new array [1, 2, 3]. The original array [3, 1, 2] stays the same.

Here is another example:

const words = ["pear", "apple", "banana"];
const sortedWords = words.toSorted();
console.log(sortedWords);

This returns a new array ["apple", "banana", "pear"]. The original array stays in its old order.

You can also sort arrays of objects with toSorted. For example:

const users = [{name: "Zara"}, {name: "Ali"}, {name: "John"}];
const sortedUsers = users.toSorted((a, b) => a.name.localeCompare(b.name));
console.log(sortedUsers);

This returns a new array sorted by name [{name:"Ali"}, {name:"John"}, {name:"Zara"}]. The original array stays in its old order.

The toSorted is part of ES2023. Modern browsers like Chrome, Edge, and Firefox include support. Older browsers may need a polyfill before use.

The Difference Between sort() and toSorted()

The sort() sorts the array in place and changes its original order. toSorted() makes a new sorted array and leaves the original unchanged.

MethodChanges Original ArrayReturns New Array
sort()YesNo
toSorted()NoYes

Use sort() when you want to change the array itself and the toSorted() when you want a new array without changes to the original.

Examples of the toString Function in JavaScript

Sort Numbers in Ascending Order:

const nums = [10, 5, 8, 1];
const sorted = nums.toSorted((a, b) => a - b);
console.log(sorted);

This shows how to sort numbers in ascending order while the original array stays the same. It returns a new array with ordered numbers.

Sort Strings by Length:

const items = ["banana", "kiwi", "apple"];
const sorted = items.toSorted((a, b) => a.length - b.length);
console.log(sorted);

This shows how to sort text by length. It returns a new array with text in order by length. The original array stays the same.

Sort Objects by Age:

const people = [{age:30},{age:20},{age:40}];
const sorted = people.toSorted((a, b) => a.age - b.age);
console.log(sorted);

This shows how to sort objects by a property. It creates a new array in order of age and does not change the original array.

Sort with Custom Compare Function:

const letters = ["b", "C", "a"];
const sorted = letters.toSorted((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}));
console.log(sorted);

This shows how to sort values with a custom compare rule. It gives a new array with values sorted without case issues and leaves the old array untouched.

Wrapping Up

You learned how toSorted creates a new array and leaves the original untouched.

Here is a quick recap:

  • sort() changes the array itself.
  • toSorted() makes a new sorted array.
  • Use each one based on whether you want to change the original array or not.

FAQs

What is JavaScript toSorted function used for?

The JavaScript toSorted function creates a new sorted array without changing the original. It is part of the ES2023 standard.


const numbers = [3, 1, 4, 2];
const sorted = numbers.toSorted();
console.log(sorted); // [1, 2, 3, 4]
console.log(numbers); // [3, 1, 4, 2]
  • sort() mutates the array
  • toSorted() returns a new array

What is the difference between sort and toSorted in JavaScript?

The difference is that sort() changes the original array while toSorted() creates a new one. This makes toSorted safer in most use cases.


const fruits = ["banana", "apple", "mango"];
const s1 = fruits.sort();
console.log(fruits); // ["apple", "banana", "mango"]

const fruits2 = ["banana", "apple", "mango"];
const s2 = fruits2.toSorted();
console.log(fruits2); // ["banana", "apple", "mango"]
console.log(s2);      // ["apple", "banana", "mango"]

How do you use toSorted function with objects in JavaScript?

You can pass a compare function inside toSorted() to sort objects by a property. This does not affect the original array of objects.


const users = [
  {name: "Alice", age: 25},
  {name: "Bob", age: 20},
  {name: "Charlie", age: 30}
];

const sortedUsers = users.toSorted((a, b) => a.age - b.age);
console.log(sortedUsers);
/*
[
  {name: "Bob", age: 20},
  {name: "Alice", age: 25},
  {name: "Charlie", age: 30}
]
*/

Is JavaScript toSorted function supported in all browsers?

The toSorted function is part of ES2023 and modern browsers support it. Older browsers may not support it without a polyfill.

  • ✅ Chrome 110+
  • ✅ Edge 110+
  • ✅ Safari 16.4+
  • ✅ Firefox 115+
  • ❌ Older browsers need polyfills

Similar Reads

JavaScript Math log: How it Works with Examples

JavaScript Math.log() was added to help people find the natural log of a number. It solves real problems in science…

JavaScript Math tan: The Tangent of an Angle in Radians

JavaScript Math.tan() finds the tangent of an angle in radians. You use it when you need to solve angle-based math.…

JavaScript valueOf Function: How it Works with Examples

You will learn what the JavaScript valueOf function does and how it works. It returns the primitive value of an…

Top 5 Code Editors: The Best IDE for JavaScript

If you are a coder, one of your primary requirements is to have a trustworthy code- editor. A Code editor…

JavaScript Math atan: Arc Tangent of a Number in Radians

Math.atan() function in JavaScript helps you to solve math problems in your code. It turns a number into an angle.…

Understanding JavaScript Objects with Examples

JavaScript Objects hold values as key and value pairs, and they help you store and access data. Understand the JavaScript…

JavaScript toReversed Function with Examples

JavaScript toReversed returns a new array with the reversed order of its elements. It does not change the original array…

JavaScript Coding Style Guide for Beginners

JavaScript code follows some rules that help both new and old developers. A project without rules in code creates trouble…

JavaScript Loops and Iteration: How They Work with Examples

You use loops in JavaScript to repeat code without copying it many times. This helps when you handle lots of…

JavaScript Math trunc: How to Removes Decimals

JavaScript gives you the Math.trunc() function to work with decimal numbers. You use it when you want to remove the…

Previous Article

Props in React explained with examples

Next Article

Git commit Command: How it Works with Examples

Write a Comment

Leave a Comment

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


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.