Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the value of an array changes original array JavaScript

The following code causes both elements from id 0 to be set to -, even though I want only one to be set to -1. Am I just creating a reference to the labelArray, or is something else?

labelArray.sort(compare);
valueArray = labelArray;
valueArray[0] = '-1';
labelArray[0] = '-';

All help is appreciated.

UPDATE (2019): It's been several years since I first did this post, and ES6 is used pretty much universally. So, I wanted to come back and add that, instead of using the slice() method recommended in the accepted answer, you can instead use array destructing in the following to make a copy:

valueArray = [...labelArray];
like image 985
OpensaurusRex Avatar asked Jan 26 '12 20:01

OpensaurusRex


1 Answers

Yes. Both valueArray and labelArray reference the same underlying array. To make a copy, use slice():

valueArray = labelArray.slice(0);

NOTE: Slice() only copies 1 level deep, which works fine for primitive arrays. If the array contains complex objects, use something like jQuery's clone(), credit @Jonathan.

like image 74
calebds Avatar answered Sep 30 '22 06:09

calebds