Standard built-ins

Array.prototype.toSorted()

Try the free JavaScript compiler

Creates an ordinary array sorted under the same comparator conventions as sort, without writing the receiver. Reads holes as undefined. It is a shallow copy; comparator side effects can still mutate objects.

Formal Syntax & Structure

javascript syntaxjavascript
array.toSorted(compareFn?)

Parameters & Attributes

NameTypeDescription
compareFnfunctionOptional ordering comparator.

Return Value

Array

New sorted array.

Working Example

Example Snippetjavascript
const a=[3,2,1]; console.log(a.toSorted((x,y)=>x-y).join(","),a.join(","));
JavaScript Reference