Search code examples
javascriptarraysmulti-index

Create a array with multiples index in JS


I need some help here. I'm trying to rewrite some codes in javascript, and I'm stuck at creating a array with a multiples indexes. Typing arbitrarily, is something like this:

Those constants are the limit of each array's index

const index1 = 2
const index2 = 20
const index3 = 18

The var 'storage' is the array that I want to create.

storage = Array[0.."index1", 0.."index2", 0.."index3"] of Bool 

Using random bool values, the array "storage" will result in :

storage[0,0,0] => true 
storage[0,0,1] => false 
storage[0,0,2] => false 
storage[0,0,3] => false 
...
storage[2,20,16] => true 
storage[2,20,17] => false 
storage[2,20,18] => true 

end of array

How create this using JavaScript?


Solution

  • You can do following using Multi-dimentional array:

    const index1 = 2;
    const index2 = 20;
    const index3 = 18;
    let storage = new Array(index1);
    for (let i = 0; i < index1; i++) {
      storage[i] = new Array(index2);
      for (let j = 0; j < index2; j++) {
        storage[i][j] = new Array(index3);
        for (let k = 0; k < index3; k++) {
          // random bool value generation
          storage[i][j][k] = (i + j + k) % 2 ? true : false;
        }
      }
    }
    // print the array
    for (let i = 0; i < index1; i++) {
      for (let j = 0; j < index2; j++) {
        for (let k = 0; k < index3; k++) {
          console.log(
            "storage[" +
            i +
            "," +
            j +
            "," +
            k +
            "] => " +
            storage[i][j][k]
          );
        }
      }
    }