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

105
Views
Function outputs different array but with same input

I'm writing a function for a battleship game that creates a 8x8 grid, and then places two 'ships' at random positions within that grid:

//generates 8x8 board
const generateBoard = () => {
    const gridRow = []
    const gridContainer = []
    for(let i=0; i<8; i++){
      gridRow[i] = ['x']
      gridContainer.push(gridRow)
    }  
    return gridContainer
}


//puts ships at two random positions
const generateBoardWithShips = (board) => { 


  for (let i=0; i<2; i++) { 
    const x = Math.floor(Math.random() * 8);     
    const y = Math.floor(Math.random() * 8);     
    board[y][x] = ['🚢']; 
    coordinates.push(x,y)
   }   
   return board 
  }

//I also have an entire grid saved to variable initialBoardState

const initialBoardState = [
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']],
    [['x'],['x'],['x'],['x'],['x'],['x'],['x'],['x']]
]

What's confusing me is this: when I pass initialBoardState as an argument to generateBoardWithShips, it works as desired and creates an 8x8 grid with ships at two random positions.
However, when I pass the output of generateBoard (also an 8x8 grid) to generateBoardWIthTwoShips, the output is an grid with two ships in the same position on every row.

I've logged the output of createBoard and it is identical to initialBoardState, so if I'm putting the exact same input into generateBoardWithTwoShips, why is it giving me different outputs?

Summary:

const grid = generateBoard()
generateBoardWithTwoShips(initialBoardState) : works fine
generateBoardWithTwoShips(grid) : prints 2 ships, but in every row
about 4 years ago · Juan Pablo Isaza
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!