1

I am trying to figure out, is there a chance to replace code below with something more simple? In my code I am creating a 10x10 game board, where I am using for, with similar approach as here:

    let arr = [];
for (let i = 0; i < 10; i++) {
      arr[i] = [];
      for (let j = 0; j < 10; j++) {
        arr[i][j] = {
          row: j,
          col: i,
          value: 0,
          color: 'rgba(0, 162, 255, 0.2)',
          elX: -1,
          elY: -1,
        };
      }
    };

Can we do it without using of for iteration?

Creating empty array is quite simple. We can find how to do it here:

And after this we can assign values like this:

arr[i][j] = {...};

But still we need to use for iteration. I have a fealing that fill might be a key to sole this problem, used in this answer, but still I have no clue how to populate the array: https://stackoverflow.com/a/49201210/12603542

bakunet
  • 559
  • 8
  • 25

1 Answers1

2

Use Array.from will simplify.

const val = (i, j) => ({
  row: j,
  col: i,
  value: 0,
  color: "rgba(0, 162, 255, 0.2)",
  elX: -1,
  elY: -1,
});

const vals2d = (len = 10) =>
  Array.from({ length: len }, (_, i) =>
    Array.from({ length: len }, (_, j) => val(i, j))
  );
  
console.log(vals2d())
Siva K V
  • 10,561
  • 2
  • 16
  • 29