0

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 ]

1 Answer 1

6

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.