Select random values from an array in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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' ]
raja
Published on 12-Sep-2020 12:26:01
Advertisements