Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array data going missing

I’m trying to create an array of objects with nested arrays, but data is going missing in the last step:

const args_arr = [];
const options_arr = [];
let options = '';

let text = "";
for (let i = 0; i < 5; i++) {
  for (let j = 0; j < 5; j++) {
    if (i === j) {
      args_arr.push(true);
    } else {
      args_arr.push(false);
    }
  }
  text += args_arr + "<br>";
  options = {
    op1: true,
    op2: false,
    args: ['visible']
  };
  text += JSON.stringify(options) + "<br>";
  options.args.push(args_arr);
  text += JSON.stringify(options) + "<br>";
  options_arr.push(options);

  args_arr.length = 0;
}
text += '<br>' + JSON.stringify(options_arr) + "<br>";

document.getElementById("demo").innerHTML = text;
<pre id="demo"></pre>

Everything works as expected, but at the last step where I push options into options_arr the arrays after ‘visible’ goes missing.

Here’s the result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

true,false,false,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[true,false,false,false,false]]}
false,true,false,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,true,false,false,false]]}
false,false,true,false,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,false,true,false,false]]}
false,false,false,true,false
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,false,false,true,false]]}
false,false,false,false,true
{"op1":true,"op2":false,"args":["visible"]}
{"op1":true,"op2":false,"args":["visible",[false,false,false,false,true]]}

[{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]},{"op1":true,"op2":false,"args":["visible",[]]}]

What am I doing wrong?

>Solution :

The problem is because you push the args_arr into the options_arr and modify the info afterwards.

Change options.args.push(args_arr); to options.args.push([...args_arr]);

What it will do is copy the values from args_arr into a new array. This way it will not reset on every loop.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading