toSorted()

noun

say it: “too SOR-tid” /tuː ˈsɔːrtɪd/

A JavaScript array method that returns a new, sorted copy of the array and leaves the original in its old order. It takes the same compare function as sort().

What is toSorted() in JavaScript?

toSorted() — An array method that returns a new, sorted copy of the array and leaves the original as it was; sort() sorts the array itself instead. Give it a compare function to sort numbers or objects.

const finishTimes = [42, 7, 19];
const fastestFirst = finishTimes.toSorted((a, b) => a - b);
console.log(fastestFirst); // [ 7, 19, 42 ]
console.log(finishTimes);  // [ 42, 7, 19 ]

In a sentence

  • “scores.toSorted((a, b) => b - a) gave me a leaderboard and kept the scores in the order they were played.”

Level: Apprentice · More JavaScript terms at this level

Updated