
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Randomly Shuffle an Array of Literals in JavaScript
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.
Advertisements