0

I am creating a Chrome extension and am getting some weird results with sorted arrays. I have two global arrays called "timearray" and "timearrayorig" (timearray is the sorted version of timearrayorig). In a function, I set a bunch of values in timearrayorig and then copy the entire array to timearray and sort timearray. For some reason, this also sorts timearrayorig. I would greatly appreciate it if someone could explain why this is the case.

for (var i = 0; i < triparray.length; i++) {
    for (var j = 0; j < trainsfeed.length; j++) {
        if (trainsfeed[j].getElementsByTagName('Trip')[0].childNodes[0].nodeValue == triparray[i]) {
            if (timearrayorig.length < i + 1 || timearrayorig[i] > Number(trainsfeed[j].getElementsByTagName('Scheduled')[0].childNodes[0].nodeValue)) {
                timearrayorig.push(Number(trainsfeed[j].getElementsByTagName('Scheduled')[0].childNodes[0].nodeValue));
            }
        }
    }
}
timearray = timearrayorig;
//timearray.sort();

(trainsfeed is a bunch of XML separated by messages and triparray is the list of all the different values for the "Trip" field. timearrayorig and timearray are the earliest times for each element of triparray from the elements of trainsfeed.)

If I run this script and find the value of timearrayorig and timearray in the debug console, they are the same, for example [1365801720, 1365801180, 1365801600, 1365802800, 1365800940]. But when I sort timearray, they both become [1365800940, 1365801180, 1365801600, 1365801720, 1365802800].

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
csander
  • 1,385
  • 10
  • 11
  • array in javascript is reference type so when you assign timearrayorig to timearray you just assign reference of array if you want to copy it try array slice method – Givi Apr 12 '13 at 21:21

2 Answers2

1
timearray = timearrayorig;

This doesn't copy the array; it creates a second variable which refers to the same array. There is still only one array, which is why sorting it affects both variables. To copy the array, do:

var timearray = timearrayorig.slice();

For more details, see: Copying array by value in JavaScript.

Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
0

timearrayorig is holding a reference to the array, so when you assign timearray = timearrayorig; both labels reference the same memory space.

If you want to copy the array you can do something like:

timearray = [];
for(var i = 0; i < timearrayorig.length; i++) timerray[i] = timearrayorig[i];
dzajdband
  • 191
  • 1
  • 4