0

I'm trying to use a for loop to modify an array then store that modification in another array than do another modification and store that to the second array etc, but my second array is just d instances of the last iteration of my for loop. This seems like a closure problem but I can't figure out a workaround?

for (var d=1; d<arr1.length; d++) {
       remove = arr1.splice(d,1).toString(); 
        arr1.splice(d+1,0,remove);
     arr2.push(arr1);
   }
    return arr2;
3
  • please add the arrays as well. Commented Feb 2, 2017 at 21:47
  • And the expected output. Commented Feb 2, 2017 at 21:48
  • I'm starting out with [1,2,3,4] as arr1 and I'm hoping to have arr2 end up as [[1,2,3,4],[1,3,2,4],[1,3,4,2]]. I think I need to change d<arr1.length to d<arr1.length-1 but that still doesn't solve my problem - I keep getting 4 sets of [1,3,4,2] as my result Commented Feb 2, 2017 at 22:06

1 Answer 1

0

If you want to store all modified versions of your array, I suggest using an array of arrays, in this case let's call that top-level array master. Each time you modify your array, you would just push it to the master array.

This would give you what is called a "2d array". Then you would be able to access any version of your array that you wanted to. Your first array would be master[0], second would be master[1], etc. To access the first element of your second array, you can then just say master[1][0].

Hope this helps!

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

3 Comments

I was trying to do that by pushing arr1 to arr2 each time?
I know your problem now. Arrays are reference objects. Read up on this stackoverflow.com/questions/1686990/…

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.