Randomly shuffling an array of literals in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals.

Then the function should shuffle the order of elements in any random order inplace.

Example

The code for this will be −

const letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const unorderArray = arr => {
   let i, pos, temp;
   for (i = 0; i < 100; i++) {
      pos = Math.random() * arr.length | 0;
      temp = arr[pos];
      arr.splice(pos, 1);
      arr.push(temp);
   };
}
unorderArray(letters);
console.log(letters);

Output

And the output in the console will be −

[
   'b', 'e', 'c',
   'a', 'g', 'f',
   'd'
]

Note that this is just one of the many possible outputs.

raja
Published on 20-Nov-2020 10:19:48
Advertisements