Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptHow to create an array with random values with the help of...

How to create an array with random values with the help of JavaScript ?

The task is to generate an array with random values with the help of JavaScript. There are two approaches which are discussed below: 

Approach 1:

  • Use Math.random() and Math.floor() methods to get the random values.
  • Push the values one by one in the array (But this approach may generate repeated values).

Example: This example implements the above approach. 

Javascript




function gfg_Run() {
    console.log(Array.from({
        length: 10
    }, () => Math.floor(Math.random() * 10)));
}
gfg_Run()


Output

[
  8, 6, 4, 3, 9,
  2, 8, 9, 7, 8
]

Approach 2:

  • Create an array and put the values in it (like 1 at index 0, 2 at index 1, and 3 at index 2 in the same order by a loop.)
  • Assign a variable (tp) = length of the array.
  • Run a loop on variable(tp).
  • Inside the loop use Math.random() and Math.floor() methods to get the random index of the array.
  • Swap this array value with the index(tp) and decrease the variable(tp) by 1.
  • Run the loop until variable(tp) becomes 0.

Example: This example implements the above approach. 

Javascript




let a = []
for ( i = 0; i < 10; ++i) a[i] = i;
 
// Array like[1, 2, 3, 4, ...]
 
function createRandom(arr) {
    let tmp, cur, tp = arr.length;
    if (tp)
 
        // Run until tp becomes 0.
        while (--tp) {
 
            // Generating the random index.
            cur = Math.floor(Math.random() * (tp + 1));
 
            // Getting the index(cur) value in variable(tmp).
            tmp = arr[cur];
 
            // Moving the index(tp) value to index(cur).
            arr[cur] = arr[tp];
 
            // Moving back the tmp value to
            // index(tp), Swapping is done.
            arr[tp] = tmp;
        }
    return arr;
}
 
function gfg_Run() {
    console.log(createRandom(a));
}
gfg_Run()


Output

[
  0, 9, 4, 3, 6,
  8, 2, 7, 1, 5
]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments