1

I try to fill the array s with 9999 different sets of values m[i][random], here is the code:

let m = [[22,0],[53,0],[64,0],[45,0],[34,0]];
let l = m.length;
let s = [];
for (let j = 0; j < 9999; j++)
{
  for(let i = 0; i < m.length; i++)
  {
    let x = Math.floor(Math.random()*l);
    m[i][1] = x; 
  }
  s.push(m);
} 

But i get the same values:

console.log(s)
[ [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ],
  [ [ 22, 0 ], [ 53, 2 ], [ 64, 0 ], [ 45, 4 ], [ 34, 1 ] ], ...]

What am I doing wrong? How to fix it?

3
  • 3
    You have to make a new copy of m on every iteration of the outer loop. Commented Dec 3, 2020 at 18:50
  • Does this answer your question? Javascript array with for loop, returns only last element Commented Dec 3, 2020 at 18:52
  • 2
    A tip for debugging issues like this: You could log the value of s for the first several iterations of the outer loop. In this case, that would have ruled out one possible problem (the same random values being produced each time) and helped identify the actual problem (the random values from the previous iterations get replaced with the ones from the latest iteration). That would get you closer to the root cause (s contains repeated references to the same array m, so new updates to m change your previous additions to s). Commented Dec 3, 2020 at 19:19

1 Answer 1

6

Create the m subarray inside the loop (so you have a separate subarray for each iteration), not outside of it - outside, you've only created a single array in memory that each index points to.

let s = [];
for (let j = 0; j < 9999; j++)
{
  let m = [[22,0],[53,0],[64,0],[45,0],[34,0]];
  let l = m.length;
  for(let i = 0; i < m.length; i++)
  {
    let x = Math.floor(Math.random()*l);
    m[i][1] = x; 
  }
  s.push(m);
}

Or, more functionally and all at once with Array.from:

const s = Array.from(
  { length: 2 },
  () => [[22,0],[53,0],[64,0],[45,0],[34,0]]
          .map(([num]) => [num, Math.floor(Math.random() * 5)])
);
console.log(s);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.