Recursive AI

Sort a JavaScript array without changing the original

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

For a sorted copy of the numbers in nums, use nums.toSorted((a, b) => a - b). In older runtimes, use [...nums].sort((a, b) => a - b).

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma;
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
const nums = [10, 2, 1];
const copy = nums.toSorted((a, b) => a - b);
`${copy}\n${nums}`;
""").AsString);

Unzip the example, then dotnet run.

Prints the sorted copy first, then the unchanged input:

Text
1,2,10
10,2,1

The full program

The download also checks that the two arrays are different objects and shows what happens when you leave out the comparator.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
const nums = [10, 2, 1];
const sorted = nums.toSorted((a, b) => a - b);
[
  'sorted: ' + sorted.join(', '),
  'original: ' + nums.join(', '),
  'same array: ' + (sorted === nums),
  'without a comparator: ' + nums.toSorted().join(', ')
].join('\n');
""").AsString);
Text
sorted: 1, 2, 10
original: 10, 2, 1
same array: false
without a comparator: 1, 10, 2

If you pass a comparator such as null instead of a function, JavaScript throws a TypeError; omit the argument if you want the default order.

Variations

Sort in descending numeric order. Replace the JavaScript inside Evaluate:

JAVASCRIPT
const nums = [2, 10, 1];
const copy = nums.toSorted((a, b) => b - a);
`${copy}\n${nums}`;
Text
10,2,1
2,10,1

Sort objects by a property. Replace the JavaScript inside Evaluate:

JAVASCRIPT
const jobs = [
  { name: 'pack', rank: 2 },
  { name: 'build', rank: 1 },
  { name: 'upload', rank: 2 }
];
const copy = jobs.toSorted((a, b) => a.rank - b.rank);
copy.map(job => job.name).join(', ');
Text
build, pack, upload

The short answer

Use array.toSorted((a, b) => a - b) for an ascending numeric sort that leaves the original array in place. Keep the returned array and use it where you need the sorted order. In a .NET app, OneEcma runs that JavaScript inside ScriptEngine.Evaluate.

Does sort() change the original array?

Yes. sort() sorts in place and returns the same array. Assigning its result to a new variable doesn’t make a copy, so any other code holding the original array sees the reorder too. toSorted() creates a separate array instead. If the same script must run where toSorted isn’t available, copy a regular dense array before calling sort():

JAVASCRIPT
const nums = [10, 2, 1];
const copy = [...nums].sort((a, b) => a - b);
`${copy}\n${nums}`;

The copy is shallow either way: if the elements are objects, changing a field on an object through the sorted array also changes what you see through the original.

toSorted() is part of ES2023; MDN’s compatibility data lists Chrome and Edge 110+, Firefox 115+, Safari 16+, and Node.js 20.0.0+.

How do you sort an array of numbers in JavaScript?

Give the sort method a function that returns a negative number when a belongs before b, a positive number when it belongs after, and zero for a tie. For finite numbers, subtracting b from a does that. The default sort compares values as strings, which is why "10" comes before "2" in the download’s last line. A comparator that only returns true or false doesn’t express both directions; use the subtraction instead.

For an array of objects, subtract the numeric fields you want to order by, as in the rank variation. When two ranks match, their original order is kept: pack still comes before upload. That is useful when the incoming order breaks ties for you. Don’t change the elements from inside the comparator; leave it to answer only which value should come first.

All oneecma recipes