Search code examples
javascriptarraysdynamic-arrays

Can I Insert an entire array in other array position in javascript?


I have an array called arr1 and a second array called arr2. Both are created dinamically (I mean arr2 is different every time enters a while and arr1 it's the same but is filled everytime by arr2 new array).

I want every postion of arr1 to have an different array (in the example arr2 is always the same but nevermind that), how can I do this?

I've tried this way:

//Some context
arr1[x] = new Array();
arr2[y] = new Array();
while(j < 10){
  arr2[j] = j;
  j++;
}
while(x < 10){
  arr1[x] = [arr2]; //problem
  x++;
}


arr1[x] = new Array(otherArr.length);

arr1[x] = [arr2]  (?)

arr1[x] = arr2 (?)

arr1[x] = new Array(arr2.length)
arr1[x] = arr2 (?)

Solution

  • for(var i=0; i<arr1.length; i++)
      arr1[i] = arr2;
    

    Edit: use for(var i=0; i<arr1.length; i++) arr1[i] = arr2.slice(0); If you want to copy the array instead of using a reference.