[javascript] Create an array with random values

How can I create an array with 40 elements, with random values from 0 to 39 ? Like

[4, 23, 7, 39, 19, 0, 9, 14, ...]

I tried using solutions from here:

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/randomizeArrayElements.htm

but the array I get is very little randomized. It generates a lot of blocks of successive numbers...

This question is related to javascript arrays random

The answer is


Using some new ES6 features, this can now be achieved using:

function getRandomInt(min, max) {
    "use strict";
    if (max < min) {
        // Swap min and max
        [min, max] = [min, max];
    }

    // Generate random number n, where min <= n <= max
    let range = max - min + 1;
    return Math.floor(Math.random() * range) + min;
}

let values = Array.from({length: 40}, () => getRandomInt(0, 40));

console.log(values);

Note that this solution will only work in modern browsers that support these ES6 features: arrow functions and Array.from().


var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
  myArray.push(Math.floor(Math.random()*limit));
}

This above is the traditional way of doing it but I second @Pointy and @Phrogz if you want to avoid duplicates in your array without having to do expensive computation


Since the range of numbers is constrained, I'd say the best thing to do is generate the array, fill it with numbers zero through 39 (in order), then shuffle it.


Here is a ES6 function that allows a min and a max and will generate an array of unique values in random order that contain all the number from min to max inclusive:

const createRandomNumbers = (min, max) => {
  const randomNumbers = new Set()
  const range = max - min + 1

  while (randomNumbers.size < range) {
    randomNumbers.add(~~(Math.random() * range))
  }

  return [...randomNumbers]
}

If you need it with random unique values from 0...length range:

const randomRange = length => {
  const results = []
  const possibleValues = Array.from({ length }, (value, i) => i)

  for (let i = 0; i < length; i += 1) {
    const possibleValuesRange = length - (length - possibleValues.length)
    const randomNumber = Math.floor(Math.random() * possibleValuesRange)
    const normalizedRandomNumber = randomNumber !== possibleValuesRange ? randomNumber : possibleValuesRange

    const [nextNumber] = possibleValues.splice(normalizedRandomNumber, 1)

    results.push(nextNumber)
  }

  return results
}

randomRange(5) // [3, 0, 1, 4, 2]

ES5:

function randomArray(length, max) {
    return Array.apply(null, Array(length)).map(function() {
        return Math.round(Math.random() * max);
    });
}

ES6:

randomArray = (length, max) => [...new Array(length)]
    .map(() => Math.round(Math.random() * max));

I needed something a bit different than what these solutions gave, in that I needed to create an array with a number of distinct random numbers held to a specified range. Below is my solution.

function getDistinctRandomIntForArray(array, range){
   var n = Math.floor((Math.random() * range));
   if(array.indexOf(n) == -1){        
    return n; 
   } else {
    return getDistinctRandomIntForArray(array, range); 
   }
}

function generateArrayOfRandomInts(count, range) {
   var array = []; 
   for (i=0; i<count; ++i){
    array[i] = getDistinctRandomIntForArray(array, range);
   };
   return array; 
}

I would have preferred to not create a loop that has the possibility to end up with a lot of unnecessary calls (if your count, and range are high and are close to the same number) but this is the best I could come up with.


Shortest :-)

[...Array(40)].map(e=>~~(Math.random()*40))


Because * has higher precedence than |, it can be shorter by using |0 to replace Math.floor().

[...Array(40)].map(e=>Math.random()*40|0)

Even shorter ES6 approach:

Array(40).fill().map(() => Math.round(Math.random() * 40))

Also, you could have a function with arguments:

const randomArray = (length, max) => 
  Array(length).fill().map(() => Math.round(Math.random() * max))

from the page suggested by @Phrogz

for (var i=0,nums=[];i<49;i++) nums[i]={ n:i, rand:Math.random() };
nums.sort( function(a,b){ a=a.rand; b=b.rand; return a<b?-1:a>b?1:0 } );

I am pretty sure that this is the shortest way to create your random array without any repeats

var random_array = new Array(40).fill().map((a, i) => a = i).sort(() => Math.random() - 0.5);

.. the array I get is very little randomized. It generates a lot of blocks of successive numbers...

Sequences of random items often contain blocks of successive numbers, see the Gambler's Fallacy. For example:

.. we have just tossed four heads in a row .. Since the probability of a run of five successive heads is only 1/32 .. a person subject to the gambler's fallacy might believe that this next flip was less likely to be heads than to be tails. http://en.wikipedia.org/wiki/Gamblers_fallacy


function shuffle(maxElements) {
    //create ordered array : 0,1,2,3..maxElements
    for (var temArr = [], i = 0; i < maxElements; i++) {
        temArr[i] = i;
    }

    for (var finalArr = [maxElements], i = 0; i < maxElements; i++) {
        //remove rundom element form the temArr and push it into finalArrr
        finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0];
    }

    return finalArr
}

I guess this method will solve the issue with the probabilities, only limited by random numbers generator.


Math.random() will return a number between 0 and 1(exclusive). So, if you want 0-40, you can multiple it by 40, the highest the result can ever be is what you're multiplying by.

var arr = [];
for (var i=0, t=40; i<t; i++) {
    arr.push(Math.round(Math.random() * t))
}
document.write(arr);

http://jsfiddle.net/robert/tUW89/


Generators

An array of length 40 of 40 random possible values (0 - 39) without repeating values is better to shuffle it as @Phrogz and @Jared Beck explain. Another approach, just for the records, could be using generators. But this approach lacks of performance compared to other proposed solutions.

function* generateRandomIterable(n, range) {
  for (let i = 0; i < n; i++) {
    yield ~~(Math.random() * range);
  }
}
const randomArr = [...generateRandomIterable(40,40)];

The shortest approach (ES6)

// randomly generated N = 40 length array 0 <= A[N] <= 39
Array.from({length: 40}, () => Math.floor(Math.random() * 40));

Enjoy!


let randomNumber = Array.from({length: 6}, () => Math.floor(Math.random() * 39));

limited the array to 6 values to make it easy to see.


Quirk single-line solutions on every day.

Values in arrays is total random, so when you will be use this snippets, it will different.

An array (length 10) with random chars in lowercase

Array.apply(null, Array(10)).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); })

[ 'k', 'a', 'x', 'y', 'n', 'w', 'm', 'q', 'b', 'j' ]

An array (length 10) with random integer numbers from 0 to 99

Array.apply(null, Array(10)).map(function() { return Math.floor(Math.random() * 100 % 100); })

[ 86, 77, 83, 27, 79, 96, 67, 75, 52, 21 ]

An array random dates (from 10 years to ago to now)

Array.apply(null, Array(10)).map(function() { return new Date((new Date()).getFullYear() - Math.floor(Math.random() * 10), Math.floor(Math.random() * 12), Math.floor(Math.random() * 29) )})

[ 2008-08-22T21:00:00.000Z, 2007-07-17T21:00:00.000Z,
2015-05-05T21:00:00.000Z, 2011-06-14T21:00:00.000Z,
2009-07-23T21:00:00.000Z, 2009-11-13T22:00:00.000Z,
2010-05-09T21:00:00.000Z, 2008-01-05T22:00:00.000Z,
2016-05-06T21:00:00.000Z, 2014-08-06T21:00:00.000Z ]

An array (length 10) random strings

Array.apply(null, Array(10)).map(function() { return Array.apply(null, Array(Math.floor(Math.random() * 10  + 3))).map(function() { return String.fromCharCode(Math.floor(Math.random() * (123 - 97) + 97)); }).join('') });

[ 'cubjjhaph', 'bmwy', 'alhobd', 'ceud', 'tnyullyn', 'vpkdflarhnf', 'hvg', 'arazuln', 'jzz', 'cyx' ]

Other useful things you may found here https://github.com/setivolkylany/nodejs-utils/blob/master/utils/faker.js


Refer below :-

let arr = Array.apply(null, {length: 1000}).map(Function.call, Math.random)
/* will create array with 1000 elements */

A little late to the party, but I use randojs.com for randomness because it makes stuff like this super easy. You can get a randomly shuffled array of numbers from 0 through 39 just like this:

_x000D_
_x000D_
console.log(randoSequence(40));
_x000D_
<script src="https://randojs.com/1.0.0.js"></script>
_x000D_
_x000D_
_x000D_

No fuss with the logistics of it all- plus it's super readable and easy to understand :)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?