0

Guys I have got into this problem while making dynamic multidimensional array and still I have no idea whats going wrong basically when I update that particular parent index of an array using javascript like

.on('click', function(){
     array[dynamicIndex] = anotherArray;
 });

So the problem is that when array[53][1,2,3] is first index assigned value in that but when I try to assign new value new index the array updated into

array[53][1,2,3,4,5,6]
array[54][1,2,3,4,5,6]

Hope you got the question if not you can visit this link.

Barmar
  • 741,623
  • 53
  • 500
  • 612
طلحة
  • 375
  • 4
  • 8
  • arrays are passed by reference, did you checked you're not assigning the same array ref to different elements in the parent array? – FrontTheMachine Jan 23 '18 at 07:25
  • If you're using the same `anotherArray` every time, you're putting references to the same array in all elements. – Barmar Jan 23 '18 at 07:29
  • No i am not assigning same array as i just want to assign the array in different index. You can visit the link for reference. @FrontTheMachine – طلحة Jan 23 '18 at 07:30
  • I didn't get please explain @Barmar – طلحة Jan 23 '18 at 07:31

1 Answers1

1

When, in your example, you use:

lightArr[parseInt(thatText)] = minArray;

you are assigning an array by reference. In this way, any change you make to the minArray will be reflected to the lightArr[parseInt(thatText)] value.

You can use this approach to solve your problem:

lightArr[parseInt(thatText)] = minArray.slice();
Omar Muscatello
  • 1,256
  • 14
  • 25