0

My program is getting a list of items (a string that is split) and grouping them by the number of "-" in the start of every phrase, putting them in different levels inside the variable quantityCreatedArray,

Since this number is changed in every click of a button, I want to store every change in the variable quantityCreatedArray,

I'm doing this trying to push arrays inside an array using the method Array.push(),

This whole part is inside a for of structure that is needed for another part of my code (not important),

The problem is that the array arrayUsed (that have all arrays from the variable quantityCreatedArray) is returning an array with arrays that have the last change in the variable quantityCreatedArray...

Since I'm using the push method to put the arrays inside arrayUsed, I tried putting the variables directly in arrayUsed using a simple for, yet, the results are the same...

Below is some sample code for you to test

menus = [
  "- LEVEL 1",
  "- - LEVEL1-1",
  "- - - LEVEL 1-1-1",
  "- - - LEVEL1-1-2",
  "- - - - LEVEL1-1-2-1",
  "- - - - - LEVEL 1-1-2-1-1",
  "- - - - LEVEL-1-2-2",
  "- - - LEVEL-1-3",
  "- LEVEL2"
];

var quantityCreatedArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var arrayUsed = [];

for (let item of menus) {
  let itemSplited = item.split(" ");
  let counter = 0;

  while (itemSplited[counter] == "-") {
    counter++;
  }

  for(let i1 = 0;i1<counter;i1++) {
    itemSplited.shift()
  }

  quantityCreatedArray[counter]++
  arrayUsed.push(quantityCreatedArray);
}

console.log(arrayUsed);

I expected a record of all changes in the variable quantityCreatedArray inside arrayUsed, but instead, I got just the last change in it.

Andreas
  • 21,535
  • 7
  • 47
  • 56
Nidilap
  • 25
  • 6
  • You are pushing the same array multiple times into `arrayUsed`, as opposed to each being a distinct array. – Scott Hunter Aug 07 '19 at 18:10
  • Hi Scott, im using a "console.log(quantityCreatedArray)" before the push method and it returns a different array everytime, so I think they are distinct arrays (unless im doing something wrong...) – Nidilap Aug 07 '19 at 18:14
  • he refers to same instance.. try `arrayUsed.push(JSON.parse(JSON.stringify(quantityCreatedArray)));` – guijob Aug 07 '19 at 18:16
  • You are *changing* `quantityCreatedArray`, not making new arrays. – Scott Hunter Aug 07 '19 at 18:16
  • Thanks guijob for the solution, it worked :D, also thanks Scott for pointing the error :p – Nidilap Aug 07 '19 at 18:19
  • 1
    for shallow copy you can use just `arrayUsed.push( quantityCreatedArray.slice() );` https://stackoverflow.com/questions/7486085/copy-array-by-value – Slai Aug 07 '19 at 18:20

0 Answers0