Search code examples
javascriptarraysrandomauto-populating

Populating a 2D array in Javascript with random numbers


I'm trying to populate a 2D array in javascript with random numbers. Although each column in the array is random, each row is identical which is not what I want (see image below). I want both rows and columns to be random.

http://eeldesigns.com/image.jpg

cols = 5;
rows = 10;

front = new Array(cols).fill(new Array(rows));

// Loop through Initial array to randomly place cells
for(var x = 0; x < cols; x++){
  for(var y = 0; y < rows; y++){
    front[x][y] = Math.floor(Math.random()*5);
  }
}
console.table(front) ;

Solution

  • The trouble is that you're not initializing the row. It's easily fixed:

    cols = 5;
    rows = 10;
    
    front = new Array(cols)// .fill(new Array(rows));
    
    // Loop through Initial array to randomly place cells
    for(var x = 0; x < cols; x++){
      front[x] = [];  // ***** Added this line *****
      for(var y = 0; y < rows; y++){
        front[x][y] = Math.floor(Math.random()*5);
      }
    }
    console.table(front) ; // browser console only, not StackOverflow's

    Update

    This is a cleaner version, somewhat similar to the one from Code Maniac, but simplified a bit:

    const randomTable = (rows, cols) => Array.from(
      {length: rows}, 
      () => Array.from({length: cols}, () => Math.floor(Math.random() * 5))
    )
    
    console.table(randomTable(10, 5)) // browser console only, not StackOverflow's