Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

175
Views
Filling multidimensional array in react

I am trying to fill 10X10 minesweeper board and I am having problems adding bombs at random coordinates. All the cells on the board have their isBomb field as true when I am using console.log Also here is the stackblitz link https://stackblitz.com/edit/react-uqcox1?file=src/components/Board.js

import React, { useEffect, useState } from 'react'

const INITIAL_CELL = {
    isClicked: false,
    isBomb: false,
    isFlagged: false,
}

const CreateInitialBoard = () => {
    let board = Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => INITIAL_CELL))
    board = AddBombs(board);
    return board;
}

const AddBombs = (board) => {
    let _board = board;
    console.log(board, "before");
    let randomX, randomY, bombsAdded = 0;

    while (bombsAdded < BOMB_COUNT) {
        randomX = Math.floor(Math.random() * BOARD_SIZE);
        randomY = Math.floor(Math.random() * BOARD_SIZE);
        _board[randomX][randomY].isBomb = true;
        bombsAdded++;
    }
    console.log(_board, "after");
    return _board
}

const BOARD_SIZE = 10;
const BOMB_COUNT = 10;

const INITIAL_BOARD = CreateInitialBoard();

export default function Board() {
    const [board, setBoard] = useState(INITIAL_BOARD);

    return (
        <div className='board'>
            {
                board.map((row, rowIndex) => {
                    return row.map((cell, cellIndex) => {
                        return (
                            <div key={`${rowIndex}-${cellIndex}`} className='cell'>
                                {rowIndex}, {cellIndex}
                            </div>
                        )
                    })
                })
            }
        </div>
    )
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have to replace

let board = Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => INITIAL_CELL))

with

let board = Array.from({ length: BOARD_SIZE }, () => Array.from({ length: BOARD_SIZE }, () => { return { ...INITIAL_CELL } })

What you did there was setting INITIAL_CELL's isBomb field to set true and then reusing it everywhere. Suggest you to check @ASDFGerte 's comment for further information.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!