gilsho
gilsho

Reputation: 921

How can I sort an array in javascript without modifying it?

array.sort() in javascript modifies the underlying array:

> a = [5,1,3]
[ 5, 1, 3 ]
> a.sort()
[ 1, 3, 5 ]
> a
[ 1, 3, 5 ]
> 

Is there anyway to sort the array not in place, so that the sorted version is returned as a copy. like this?

> a = [5,1,3]
[ 5, 1, 3 ]
> b = a.some_function()
[ 1, 3, 5 ]
> a
[ 5, 1, 3 ]
> b
[ 1, 3, 5 ]

Upvotes: 0

Views: 864

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

Not without writing your own function to do it. You can, of course, clone and then sort:

var b = a.slice(0).sort();

Example:

var a = [5,1,3];
var b = a.slice(0).sort();
snippet.log("a: " + JSON.stringify(a));
snippet.log("b: " + JSON.stringify(b));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Upvotes: 6

Related Questions