Home > Back-end >  How to create multiple arrays of random numbers in js?
How to create multiple arrays of random numbers in js?

Time:04-17

I am attempting to create a matrix of 3 arrays with 10 elements in each array. Each element should be a random number between 1 and 10. I wanted to use a single function to generate each of the arrays, and used this:

var array1 = [];
var array2 = [];
var array3 = [];

var tempName;

function fcnArrayGenerate(){
    let i = 1;
    while (i < 4){
        tempName = "array"   i;
        let j = 0;
        while (j < 10){
            tempName.push((Math.floor(Math.random() * 10)   1));
            j  ;
        }
        i  ;
    }
    console.log(array1);
    console.log(array2);
    console.log(array3);
}

However, when I run the function, I receive an error stating that "tempName.push is not a function." Any assistance on how to correct this would be appreciated. Thank you.

CodePudding user response:

Instead of using three variables for three different arrays, you can use a single multidimensional array to store those three arrays.

let array = [[], [], []];

function fcnArrayGenerate() {
  let i = 0;
  while (i <= 2) {
    let j = 0;
    while (j < 10) {
      array[i].push(Math.floor(Math.random() * 10)   1);
      j  ;
    }
    i  ;
  }
}
// call the function
fcnArrayGenerate();
// now print the arrays as tables
console.table(array);
console.table(array[0]);
console.table(array[1]);
console.table(array[2]);

Note: console.table() allows you to print out arrays and objects to the console in tabular form.

CodePudding user response:

If you want to push into tempName you have to initialise it with an empty array first. Right now it’s undefined. Hence you’re seeing the error as you can’t push something to undefined

Do this: var tempName = []

CodePudding user response:

To make variable names incremental, you can pass them as objects.

var data = {
  array1: [],
  array2: [],
  array3: []
}

function fcnArrayGenerate(){
    let i = 1;
    while (i < 4){
        let j = 0;
        while (j < 10){
            data['array'   i].push((Math.floor(Math.random() * 10)   1));
            j  ;
        }
        i  ;
    }
    console.log(data.array1);
    console.log(data.array2);
    console.log(data.array3);
}

fcnArrayGenerate();

  • Related