1

I am trying the below line of codes. I want to save the numbers after each iteration of outer while loop in an array named sn. But, after each iteration sn contains only the numbers of last iteration. May be I am missing whole concept of sync and async.

function test() {
  var numbers = [0, 2, 7, 0];
  var check = true;
  var sn = [];
  var p = 0;
  while (check) {
    var index = numbers.indexOf(Math.max(...numbers));
    var value = Math.max(...numbers);
    numbers[index] = 0;
    for (var i = value; i > 0; i--) {
      var temp = ++index;
      index = temp % (numbers.length);
      numbers[index] += 1;
    }
    console.log("numbers", numbers);
    if (sn.includes(numbers)) { check = false };
    sn.push(numbers);
    console.log("hey there=========");
  }
  

}  
test();
geekybot
  • 128
  • 10

2 Answers2

4

There is nothing to do with sync or async here.

Here what is happening is that, you are trying to push 'numbers' array to 'sn' array.

Statement is "sn.push(numbers);"

So here we are pushing the Object reference of numbers array to 'sn', means you are not making a copy of numbers array and pushing to 'sn'. You are just pushing the Memory reference of 'numbers' array.

So during first iteration, 'sn' will have exact value as you calculates.

But during the second iteration 'sn' will have two arrays. But those two values are same and points to the same memory location of 'number'.

So here what you should do is create a clone of 'numbers' array during each iteration.

if (sn.includes(numbers)) { check = false };

var cloneArray = numbers.slice(0);

sn.push(cloneArray);

Rony Cherian
  • 114
  • 3
1

This if statement: if (sn.includes(numbers)) { check = false }; will never be true because the Array.prototype.includes() method does not accept an array as a parameter; only individual elements. numbers is an array and thus will never be truthy.

If you are trying to see if an array contains a sub-array. The answer that Mild Fuzz has in this stack overflow: Javascript array contains/includes sub array should work.

Sasha K.
  • 287
  • 2
  • 8
  • `if (sn.includes(numbers)) { check = false };` this line executes and produces expected result. After each iteration of while loop an array `numbers` is getting generated I want to push that array each time in another array `sn`. So finally I get an array `sn` which is containing all the previous `numbers` array as each element. – geekybot Jul 16 '18 at 12:26
  • Thanks @Sasha it helps. – geekybot Jul 16 '18 at 12:32