HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Generate a JavaScript array of random integers in a given range

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascriptrangegivengeneraterandomintegersarray

Problem

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.

Solution

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 ]

Code Snippets

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 ]

Context

From 30-seconds-of-code: random-integer-array-in-range

Revisions (0)

No revisions yet.