Michael
Michael

Reputation: 143

How to create multiple arrays of random numbers in js?

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.

Upvotes: 3

Views: 715

Answers (3)

s.kuznetsov
s.kuznetsov

Reputation: 15213

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();

Upvotes: 0

Amit
Amit

Reputation: 1143

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.

Upvotes: 2

ABGR
ABGR

Reputation: 5205

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 = []

Upvotes: 1

Related Questions