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].

1
  • 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 Commented Apr 12, 2013 at 21:21

2 Answers 2

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.

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

1 Comment

you can omit 0 and use just slice()
1

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];

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.