JS: Array.prototype.toSorted
(new in JS: ECMAScript 2023)
Array.prototype.toSorted
is similar to
Array.prototype.sort
but returns a copy.
// sort array as numbers const aa = [9, 40, 2]; const bb = aa.toSorted((x, y) => { if (x < y) return -1; if (x > y) return 1; if (x == y) return 0; }); // aa not changed console.log(JSON.stringify(aa) === "[9,40,2]"); console.log(JSON.stringify(bb) === "[2,9,40]");