random list of fruits in javascript

To create a random list of fruits in JavaScript, you can start by defining an array that contains the different fruits you want to use. For example:

index.tsx
const fruits = ['apple', 'banana', 'orange', 'kiwi', 'pineapple'];
67 chars
2 lines

Then, you can write a function that shuffles this array in a random order. One way to do this is by implementing the Fisher-Yates shuffle algorithm. Here's an example implementation of this function:

index.tsx
function shuffle(array) {
  let currentIndex = array.length;
  let temporaryValue;
  let randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}
498 chars
21 lines

Now, you can simply call this shuffle function with your fruits array, and it will return a new array with the same fruits in a random order:

index.tsx
const randomFruits = shuffle(fruits);
console.log(randomFruits); // e.g. ['orange', 'kiwi', 'pineapple', 'banana', 'apple']
124 chars
3 lines

This way you can generate a random list of fruits every time you call the shuffle function.

gistlibby LogSnag