0

I have an initial array,

I've been trying to change values (orders) by using pop, splice methods inside a for loop and finally I push this array to the container array. However every time initial array is values are pushed. When I wrote console.log(initial) before push method, I can see initial array has been changed but it is not pushed to the container.

I also tried to slow down the process by using settimeout for push method but this didnt work. It is not slowing down. I guess this code is invoked immediately

I would like to learn what is going on here ? Why I have this kind of problem and what is the solution to get rid of that.

function trial(){ 
    let schedulePattern = [];
    let initial = [1,3,4,2];
    for(let i = 0; i < 3; i++){
        let temp = initial.pop();
        initial.splice(1,0,temp);   
        console.log(initial);
        schedulePattern.push(initial);
    }
    return schedulePattern;
}

**Console.log**
(4) [1, 2, 3, 4] 
(4) [1, 4, 2, 3] 
(4) [1, 3, 4, 2] 

(3) [Array(4), Array(4), Array(4)] 
0 : (4) [1, 3, 4, 2] 
1 : (4) [1, 3, 4, 2] 
2 : (4) [1, 3, 4, 2] 
length : 3
Caner Sezgin
  • 328
  • 3
  • 16

3 Answers3

0

When you push initial into schedulePattern, it's going to be a bunch of references to the same Array object. You can push a copy of the array instead if you want to preserve its current contents:

schedulePattern.push(initial.slice(0));

Good answer on reference types versus value types here: https://stackoverflow.com/a/13266769/119549

Jacob
  • 77,566
  • 24
  • 149
  • 228
0

When you push the array to schedulepattern, you are passing a reference to it. you have to "clone" the array.

use the slice function.

function trial(){ 
    let schedulePattern = [];
    let initial = [1,3,4,2];
    for(let i = 0; i < 3; i++){
        let temp = initial.pop();
        initial.splice(1,0,temp);   
        console.log(initial);
        schedulePattern.push(initial.slice());
    }
    return schedulePattern;
}
​
cesargroening
  • 323
  • 2
  • 6
  • `splice` is the wrong method. `[6, 2, 7, 2, 3].splice()` becomes `[]`. `.slice` is what you want. – Jacob Aug 01 '18 at 23:26
0

You have to know that arrays are mutable objects. What does it mean? It means what is happening to you, you are copying the reference of the object and modifying it.

const array = [1,2,3]
const copy = array;

copy.push(4);

console.log(array); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3, 4]

There are a lot of methods in Javascript which provide you the way you are looking for. In other words, create a new array copy to work properly without modify the root.

const array = [1,2,3]
const copy = Array.from(array);

copy.push(4);

console.log(array); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]

I encourage you to take a look at Array methods to increase your knowledge to take the best decision about using the different options you have.

carlosnufe
  • 121
  • 2