-4

Here I try to understand how to create array of arrays: I created one array but how to create an array of arrays, in which every array has 10 random numbers?

var arrRand = [];
    while(arrRand.length < 10){
        var random = Math.floor(Math.random() * 10) + 1;
        if(arrRand.indexOf(random) === -1) arrRand.push(random);
    }
    console.log(arrRand);
Xena
  • 379
  • 3
  • 9
  • 2
    Already have plenty of answers here on stackoverflow for such questions, break it down into 2 questions and google it – vsync Apr 24 '20 at 09:25
  • [best way to generate empty 2D array](https://stackoverflow.com/q/6495187/104380) – vsync Apr 24 '20 at 09:26
  • [Creating array of length n with random numbers](https://stackoverflow.com/q/34966459/104380) – vsync Apr 24 '20 at 09:28
  • `Array(4).fill( Array(10).fill( Math.floor(Math.random() * 10)) )` it will be 4 x 10 array of random numbers – Mechanic Apr 24 '20 at 09:28
  • 1
    @Leonardo Your solution would be great if it wouldn't use the same number to fill the arrays. – Niklas E. Apr 24 '20 at 09:36
  • 1
    @NiklasE. good point ; btw see how people copy paste this inaccurate comment into answers – Mechanic Apr 24 '20 at 09:39

4 Answers4

2

A functional approach with every number being random.

let x = Array(4).fill().map(
  () => Array(10).fill().map(
    () => Math.floor(Math.random() * 10)
  )
);

console.log(x);
Niklas E.
  • 1,848
  • 4
  • 13
  • 25
1

You can use Math.random and a nested for loop. Here is an example:

let arr = [];
for(let i = 0; i < 4; i++){
     let current = [];
     for(let j = 0; j < 10; j++)
          current.push(Math.floor(Math.random() * 10));
     arr.push(current);
}
console.log(arr)
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

In order to keep clean and dry code, you can use map function in ES6 syntax.

 const x = [...Array(6)].map(
    () => [...Array(10)].map(
        () => Math.floor(Math.random() * 10) + 1
    )
 )

console.log(x)
Kevin Lee
  • 332
  • 2
  • 13
  • Interesting how you're using `[...Array(10)]` instead of `Array(10).fill()` to make them mappable, but that's not better actually: It only saves 2 characters and it is less efficient, because the interpreter would initialize two arrays, iterating through the inner to generate the outer. I would stick to my answer. – Niklas E. Apr 24 '20 at 10:03
  • `[...Array(6)]` is useless redundant version of `Array(6)` – Mechanic Apr 24 '20 at 10:17
  • @NiklasE. yeah; correct; it's not. btw I'm seeing people mindlessly over-using the spared syntax everywhere; not here btw; it's legit. but I prefer Array.fill() – Mechanic Apr 24 '20 at 10:23
  • By using spread syntax, the code is more consistent and clear because we can notice easily ```[...Array(6)]``` as it is an array in the map function. Not a big deal with the code performance but it brings a clean code and intuitive sense. – Kevin Lee Apr 24 '20 at 10:52
-1
let a = Array(4).fill(Array(10).fill(null))

Then fill it with Math.random() in loop