I have a 2D array in a React project defined in state/the constructor that looks like this:
constructor(props){
super(props);
this.state = {
boardHeight: 50,
boardWidth: 30,
iterations: 10,
reset: false,
alive: false,
board: [],
randomNum: ''
};
this.state.board = new Array(this.state.boardHeight).fill(new Array(this.state.boardWidth).fill(0));
}
Later on in my program I want to fill the 2D array with a random number between 0 and 1. If I use the .map function I can put a random number into the array like this:
componentDidMount = () => {
const data = this.state.board;
// Generates Array of random numbers
const startingBoard = data.map(Math.random)
console.log('Starting board contains ' + startingBoard);
// After startingBoard is working I can set state with startingBoard
this.setState({
board: startingBoard
});
}
const startingBoard = data.map(Math.random)
successfully puts random numbers into one dimension of the 2D array. How can I nest a second .map function so that I can create random numbers for both dimensions of this array?
I am using this array for a game board grid. I need to generate random numbers for any square in the grid (i.e. [0][0], [0][1], etc...), so I need to be able to create random numbers for both arrays within this 2D array.
Something like this:
const starting - data.map((x, index) => {
x.map((y, index) => {
return Math.random;
})
})