Search code examples
javascriptarraysrandom

How to return objects from array in random order on every render?


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.


Solution

  • 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