1

So i want to create a chess board by doing a bidemensional array (array in array) but when i try creating it, the array comes out like [0,1] [0,2].... when i would like for it to be [[0,1,2,3...],[0,1,2,3...]...] i dont know if im making myself clear but here is the code, hopefully someone can tell me what am i doing wrong

generarTablero = (tablero) => {
    for (var i  = 0; i < 8; i++) {
        // tablero.push([i])
        for (let j = 0; j < 8; j++) {
            tablero.push([i, j])
            
        }
    }
    return tablero
}

generarTablero(tablero);
console.log(tablero)
Tomás
  • 17
  • 4
  • 1
    Could you please add a [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) – 0stone0 Dec 22 '20 at 15:40

2 Answers2

0

Just push on each array[i] like this,

generarTablero = (tablero) => {
    for (var i  = 0; i < 8; i++) {
        tablero[i] = [];
        for (let j = 0; j < 8; j++) {
            tablero[i].push(j)
            
        }
    }
    return tablero
}

tablero = generarTablero([]);
console.log(tablero)
Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30
0

You're pushing all the elements to a separate array (tablero.push([i, j])).

What you're trying to do, is to create a separate array for each 'row'. Using a tmp array variable, your code could look something like this:

generarTablero = () => {
    let arr = [];
    for (var i  = 0; i < 8; i++) {
        let tmp = [];
        for (let j = 0; j < 8; j++) {
            tmp.push(j);
        }
        arr.push(tmp);
    }
    return arr;
}

const tablero = generarTablero();
console.log(tablero)

Of course this could be simplified, using the index instead of a tmp array.

0stone0
  • 34,288
  • 4
  • 39
  • 64