1

I have a problem with my JS function. For simplification, I want to fill an array (arr1) with n other arrays (arr2). In my loop I use a counter for the current postion in arr1 (cant use arr1.push for a reason). If I log all my arr2's in arr1 they are all the same, always the last one that was added. So I wrote a basic script to test it. I always log the first element and incement the counter. I'm new to JS, is there some huge misunderstanding I don't get?

function test(){
	var arr1 = [];
	var arr2 = [];
	var counter=1;
	arr2[0]="first";
	arr2[1]="first";
	arr2[2]="first";
	arr1[0]=arr2;
  arr1[0].forEach(function(elem){console.log(elem);});
	for (var i = 0; i < 10 ; i++) {
		arr2[0]=counter;
		arr2[1]=counter;
		arr2[2]=counter;
		arr1[counter]=arr2;
    
		arr1[0].forEach(function(elem){console.log(elem);});
		counter++;
	}
}
<button onclick="test()">Click</button>

2
  • 1
    You have to make a new arr2 each time through the loop. Commented Oct 21, 2018 at 18:54
  • 1
    ... because arr1[0] = arr2; does not make a copy of arr2. Commented Oct 21, 2018 at 18:55

2 Answers 2

1

You can try to use the spread operator.

arr1[0]=[...arr2];
arr1[counter]=[...arr2];

An array is a reference type, so you always refer to the base, you don't put a copy of it inside of arr1 but a reference to the arr2.

You want a copy of arr2 to be assigned to arr1.

You can do this by creating a new Array, or more modern the ... spread operator

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

Comments

0

As Pointy said it, it just referenced the arr2 and doesn't create a copy.

So you need to

arr2=new Array();

at the beginning of the loop.

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.