3

This code seems straightforward enough

let arr = [1,2,3,4,5,6]
let store = [];

for(i = 0; i < arr.length; i++){
  console.log(arr)
  store.push(arr)
  arr.push(arr.shift())
}
console.log('store', JSON.stringify(store))

I'm expecting it to return

[[1,2,3,4,5,6],[2,3,4,5,6,1],[3,4,5,6,1,2],[4,5,6,1,2,3],[5,6,1,2,3,4],[6,1,2,3,4,5]]

But when the loop is complete, it shows

[[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]]

When printing the values in the console, they appear correct, but when the store variable is logged, they are all reordered.

[1, 2, 3, 4, 5, 6]
[2, 3, 4, 5, 6, 1]
[3, 4, 5, 6, 1, 2]
[4, 5, 6, 1, 2, 3]
[5, 6, 1, 2, 3, 4]
[6, 1, 2, 3, 4, 5]

Why is this occurring?

There is a similar question here, but it doesn't really provide an answer for my case.

Creating a pair of arrays from an array resulting in circular array

dmgig
  • 4,400
  • 5
  • 36
  • 47

5 Answers5

3

Just make sure you are inserting not the same reference to your array:

let arr = [1,2,3,4,5,6]
let store = [];

for(i = 0; i < arr.length; i++){
  store.push(Array.from(arr))  // <-- Make sure not the same ref
  arr.push(arr.shift())
}
console.log('store', JSON.stringify(store))
Akrion
  • 18,117
  • 1
  • 34
  • 54
1

store contains the same instance of arr 6 times. You modify it and print it every time, then add the same object to store, then modify it again.

To get your desired behaviour you need to add a new instance every time e.g. by cloning it when you add it.

George Helyar
  • 4,319
  • 1
  • 22
  • 20
1

You could push a copy which does not keep the same object reference.

let arr = [1, 2, 3, 4, 5, 6]
let store = [];

for (i = 0; i < arr.length; i++) {
  store.push(arr.slice())                // just take a copy
  arr.push(arr.shift())
}
console.log(store.map(a => a.join(' ')))
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Alternate approach leaving original array untouched and using splice() to remove beginning elements and concat() to add to the end

let arr = [1,2,3,4,5,6];

let store = arr.map((_,i)=> {
   let a = arr.slice();
   return i ? a.concat(a.splice(0,i)) : a;
})

console.log(JSON.stringify(store))
charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

On every loop, you are pushing the reference of the array to store

Example:
Loop - reference of arr - 0x112, then store[ i ] = reference to 0x112

At end:
arr - refer to 0x112 - value = [1, 2, 3, 4, 5, 6]

store[ ] = [ref(0x112), ref(0x112), ref(0x112), ref(0x112), ref(0x112), ref(0x112)]

Use this:

let arr = [1,2,3,4,5,6]
let store = [];

for(i = 0; i < arr.length; i++){
  console.log(arr)
  let newArr = arr.slice();
  store.push(newArr)  
  arr.push(arr.shift())
}
console.log('store', JSON.stringify(store))
Ank
  • 786
  • 1
  • 5
  • 14