0

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) ;
Ismail
  • 25
  • 5
  • Possible duplicate of [Array.prototype.fill() with object passes reference and not new instance](https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance) – Sebastian Simon Feb 04 '19 at 20:04
  • `.fill(new Array(rows))` creates a single array instance and assigns it to each column. So when you think you modify only one you actually modify all of them. It's as if you were doing this: https://jsfiddle.net/ejqc4z8x/ – Alexey Lebedev Feb 04 '19 at 20:18

3 Answers3

2

One way of doing this using map

let op = new Array(10)
         .fill(0)
         .map(e=>(new Array(5)
         .fill(0)
         .map(e=> Math.floor(Math.random() * 5))))

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

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
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103
0

This can be accomplished using a combination of Array.prototype.fill() and Array.prototype.map():

new Array(rows).fill([]).map(x => Array(columns).fill(0).map(x => x + Math.floor(Math.random() * (max - min)) + min));

For example, we can create a 100 by 964 column array full of random numbers between 900 and 1000 using the following:

new Array(100).fill([]).map(x => Array(964).fill(0).map(x => x + Math.floor(Math.random() * (1000 - 900)) + 900));
Alex
  • 51
  • 4