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' ]
Updated on: 2020-09-12T08:56:31+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements