Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a 2d array with only two elements and randomize it?

I’ve created a 2d array where subArrays include only 0 and 1 generated via Math.random() function. Currently it’s implemented with for loops.
Now I’m trying to get the same output using es6 functions, but could’t solve it.

Here is the solution with for loops

const rows = 25;
const cols = 35;

const randomGrid = () => {
  const grid = [];
  for (let i = 0; i < rows; i++) {
    const row = [];
    for (let j = 0; j < cols; j++) {
      row.push(Math.floor(Math.random() * 2));
    }
    grid.push(row);
  }
  return grid;
};

console.log(randomGrid())

And here I am trying to achieve the same output with modern js functions.
I managed only two create the 2d Array, but could’t populate with 0 and 1 in random order. Currently elements are undefined.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const rows = 25;
const cols = 35;

const randomTwoDArr = (numOfRows, numOfCols) => {
  const grid = [];
  return Array(numOfRows)
    .fill()
    .map((row) => Array(numOfCols));
};

console.log(randomTwoDArr(rows, cols));

Any help will be appreciated.

>Solution :

You can do this using Array.from as:

const rows = 25;
const cols = 35;

const randomGrid = () => {
    return Array.from({ length: rows }, () => {
        return Array.from({ length: cols }, () => Math.floor(Math.random() * 2));
    });
};

console.log(randomGrid());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading