Computer >> Computer tutorials >  >> Programming >> Javascript

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}]