
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
Select Random Values from an Array in JavaScript
To select random values from an array, use the concept of Math.random().
Example
var subjectNames = ["Javascript", "MySQL", "Java", "MongoDB", "Python","Spring Framework"]; for(var index = subjectNames.length - 1; index > 0; index--){ var rndIndex = Math.floor(Math.random() * (index + 1)); var subjNameTemp = subjectNames[rndIndex]; subjectNames[rndIndex] = subjectNames[index]; subjectNames[index] = subjNameTemp; } var getRandomSubjectName = subjectNames.slice(0, 3); console.log(getRandomSubjectName);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo178.js.
Output
This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo178.js [ 'Javascript', 'MySQL', 'Python' ]
Advertisements