---
title: "Sort a JavaScript array without changing the original"
url: https://recursiveai.org/oneecma/cookbook/sort-javascript-array-without-mutating/
description: "Sort a JavaScript array without changing the original. Run Array.prototype.toSorted with a numeric comparator in C# and see the sorted copy and input side by side."
version: "1.1.1"
---

# 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneEcma) · [GitHub](https://github.com/recursive-ai-oss/oneecma-csharp) · [Docs](https://recursiveai.org/oneecma/docs/) · [Download example (.zip)](https://recursiveai.org/oneecma/cookbook/sort-javascript-array-without-mutating/sort-javascript-array-without-mutating.zip)

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)`.

```shell
dotnet add package RecursiveAI.OneEcma
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
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](https://recursiveai.org/oneecma/cookbook/sort-javascript-array-without-mutating/sort-javascript-array-without-mutating.zip), 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.

```csharp
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
```

## Related recipes

- [Run JavaScript in C#](https://recursiveai.org/oneecma/cookbook/run-javascript/)
- [Sort JavaScript strings with locale collation](https://recursiveai.org/oneecma/cookbook/sort-javascript-strings-with-locale-collation/)

## 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()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/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()`](https://tc39.es/ecma262/2023/#sec-array.prototype.tosorted) is part of ES2023; [MDN’s compatibility data](https://github.com/mdn/browser-compat-data/blob/main/javascript/builtins/Array.json) 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.
