Skip to content

Home

Generate a JavaScript array of random integers in a given range

We've previously covered how to generate a random integer or number in a given range. But how about generating an entire array of integers in a specified range?

As you might expect, this is just a matter of repeating the process for generating an integer in the given range. You can use Array.from() to create an empty array of the specific length and then use Math.random() to generate random numbers and map them to the desired range, using Math.floor() to make them integers.

const randomIntArrayInRange = (min, max, n = 1) =>
  Array.from(
    { length: n },
    () => Math.floor(Math.random() * (max - min + 1)) + min
  );

randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]

More like this

Start typing a keyphrase to see matching snippets.