

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to shuffle an array in a random manner in JavaScript?
_.shuffle()
_.shuffle is a function belongs to underscore.js, a framework of javascript. This function actually employs the Fisher-Yates shuffle algorithm to shuffle the elements in a random manner.
syntax
_.shuffle(array);
This method takes an array as a parameter and shuffles it to get the elements in a random manner. It uses the Fisher-Yates shuffle algorithm to shuffle the arrays. For a single input, it produces various random outputs.
Example
<html> <body> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script> </head> <body> <script> document.write(_.shuffle(["raj", "pankaj", "rahim", "rachel", "Balakrishna"])) </script> </body> </html>
Output
rahim,Balakrishna,pankaj,raj,rachel
It can also shuffle large objects using Fisher-Yates shuffle algorithm. For a single input, it gives out various outputs.
Example
<html> <body> <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script> </head> <body> <script> var people = [ {"name": "Ram", "age": 27}, {"name": "Rahim", "age": 28}, {"name": "Rakul", "age": 29}, {"name": "Rohti", "age": 21} ] document.write(JSON.stringify(_.shuffle(people, 'age'))); </script> </body> </html>
Output
[{"name":"Rahim","age":28},{"name":"Rakul","age":29},{"name":"Ram","age":27},{"name":"Rohti","age":21}]
- Related Questions & Answers
- How to randomize (shuffle) a JavaScript array?
- How to shuffle an array in Java?
- Shuffle an Array in Python
- JavaScript - How to pick random elements from an array?
- Checking the intensity of shuffle of an array - JavaScript
- Shuffle an Array using STL in C++
- how to shuffle a 2D array in java correctly?
- Select random values from an array in JavaScript?
- How to do Butterfly Shuffle in JavaScript?
- Java Program to shuffle an array using list
- How to print star pattern in JavaScript in a very simple manner?
- Substitute random items in a JavaScript array?
- Alternative shuffle in JavaScript
- Shuffle Array Contents
- How to shuffle a List in Java
Advertisements