1

I have a matrix of arrays and I want to populate each array with different random numbers, I've tried to use fill() method, but it set only one number for each array, while I want to set all different numbers. Here is the link on my pen and the code I've problem with:

let matrix = [];

function matrixItem() {
    let a = +prompt("How many arrays should matrix include?");
    let reg = /^\d+$/;
    if (reg.test(a) && (typeof (a)) != null && a != '' && a <= 10) {
      for (let i = 0; i < a; i++) {
        matrix.push((Array(Math.floor(Math.random() * 5) + 1)
        /* problem is here */.fill(Math.round(Math.random() * 100))));
      }
      let sum = matrix.map(function (x) {
        return x.reduce(function (a, b) {
          return a + b;
        });
      });
      console.log(sum);
    } else matrixItem();
  }
matrixItem();

Any help would be appreciated.

1
  • The fill() method fills all the elements of an array with a static value. Use Array.from instead Commented May 5, 2019 at 10:24

1 Answer 1

2

Array#fill takes a constant value and fills the array with this value.

For getting a dynamic array with random values, you could take Array.from and map the random values.

var array = Array.from(
        { length: Math.floor(Math.random() * 5) + 1 },
        () => Math.round(Math.random() * 100)
    );

console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.