I had a problem that was making the original array to change, the curious thing is that adding arr.join("...").split("...") seems to prevent this:
A little background:
- my script creates and adds stuff to an
array - this array initialized empty like
arr=[] - the things are added passing
arr[index] = "..." - then I want to have a copy of the
arrbut sorted - when I do the sorting, the orignial
arris modified
Here is a simplified version of what is going on:
var arr=[], sorted;
arr[0] = "hello";
arr[1] = "world";
//buggy, the original is sorted
//sorted = arr.sort(function(a,b){return (a.length-b.length);});
sorted = arr.join("improbableCollision").split("improbableCollision").sort(function(a,b){return (a.length-b.length);});
- Why adding
.join("*").split("*")solves the problem? - What was causing the problem?
- Is there a more elegant way to fix this?
For the full script, check this jsFiddle
To sort without all that joining and splitting, copy the array with slice or concat:
var sorted = arr.slice(0).sort()