-1

I have an array with N numbers of element. For example this one:

let i = 0;
while(i <= 40){
    console.log(i++)
}

This will always return list of numbers from 0 to 40,what I want to achieve is to order numbers in random order every time I run the function.

Enza
  • 21
  • 5
  • 2
    create an array of numbers 0...40 ... [shuffle it](https://stackoverflow.com/a/2450976/5053002) ... output the array as required – Jaromanda X Aug 11 '23 at 06:49
  • This is a [massive dupe](https://www.google.com/search?q=shuffle+OR+randomize+array+javascript+site:stackoverflow.com) – mplungjan Aug 11 '23 at 07:19

1 Answers1

-1

You can shuffle an array of numbers in pure JavaScript using the Fisher-Yates shuffle algorithm. Here’s an example of how you can implement it:

function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
   }
}
let numbers = Array.from({length: 41}, (_, i) => i);
shuffleArray(numbers);

console.log(numbers);

This code creates an array of numbers from 0 to 40 using the Array.from() method, then shuffles the elements of the array using the shuffleArray function, which implements the Fisher-Yates shuffle algorithm

LauJk_78
  • 24
  • 4