- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 shuffling 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.
- Related Articles
- Shuffling string based on an array in JavaScript
- Sorting an array of literals using quick sort in JavaScript
- Picking index randomly from array in JavaScript
- Flattening a deeply nested array of literals in JavaScript
- Removing duplicates from a sorted array of literals in JavaScript
- How to exclude certain values from randomly generated array JavaScript
- Changing color randomly in JavaScript
- Tagged Template Literals in JavaScript
- Object literals vs constructors in JavaScript
- Function to choose elements randomly in JavaScript
- Java Program to create an array with randomly shuffled numbers in a given range
- Smallest number formed by shuffling one digit at most in JavaScript
- C++ Program to Implement Fisher-Yates Algorithm for Array Shuffling
- Is it correct to use JavaScript Array.sort() method for shuffling?
- ES6/ECMA6 template literals not working in JavaScript?

Advertisements