shuffle array in javascript and reverse it in javascript

To shuffle an array in JavaScript, we can use the Fisher-Yates shuffle algorithm. Here's an implementation of the algorithm:

index.tsx
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]];
  }
  return array;
}
200 chars
8 lines

To use this function, simply pass in an array as an argument, like so:

index.tsx
const myArray = [1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(myArray);
console.log(shuffledArray); // [3, 2, 4, 1, 5] (example output)
142 chars
4 lines

To reverse an array, we can use the reverse method that is built-in to JavaScript arrays:

index.tsx
const myArray = [1, 2, 3, 4, 5];
myArray.reverse();
console.log(myArray); // [5, 4, 3, 2, 1] (example output)
110 chars
4 lines

gistlibby LogSnag