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


array.sort() in javascript modifies underlying array:

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

is there anyway sort array not in place, sorted version returned copy. this?

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

not without writing own function it. can, of course, clone , then sort:

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

example:

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


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

[C++][SFML 2.2] Strange Performance Issues - Moving Mouse Lowers CPU Usage -

ios - Possible to get UIButton sizeThatFits to work? -