简体   繁体   中英

Picking random values from array and creating new array

I have an array, and need to pick three random values from that array. These will the be put in a new array and I will be able to see the new array on my website. I also have to make sure that no value gets picked twice.

This is what I have so far:

 var student = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
 var velg = student[Math.floor(Math.random() * student.length)];

I'm thinking I should add an id to my HTML, so the new array will show on my website, but I'm not sure about the rest.

First sort it randomly and then get first three:

student
   .sort(function(){
       return Math.random() - 0.5;
     })
   .slice(0,3)

Since Math.random() returns random value between 0 and 1, while sort expects values to be positive or negative to determine order we, we need to subtract 0.5 to make those negatives possible.

You could try something like this in a loop

var students = ["Hans","Ole","Nils","Olav","Per","Knut","Line","Pia"];
var randomStudents = [];
for(var i = 0; i < 3; i++) {
    var velg = student[Math.floor(Math.random() * students.length)];
    randomStudents.push(velg);
}

Note that this can add duplicate students to the array. You should check if student is already in the array and try again.

Keyword for that would be recursion.

https://www.codecademy.com/courses/javascript-lesson-205/0/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM