Tutorialspoint

1 Answer
vineeth.mariserla

_.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

Live Demo

<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

Live Demo

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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.