Home > Blockchain >  Javascript how to randomly select a specific amount of objects?
Javascript how to randomly select a specific amount of objects?

Time:09-22

I have created a function that returns the login names of random users located on the following api website(https://api.github.com/users)

<script>
fetch('https://api.github.com/users').then(function(response) {
 
    response.json().then(function(users){
    document.write("Highlighred Github users")
    users.forEach(function(user){ 

for (let i=0; i< 8; i  ) {
   document.write('<br>')
   document.write((users[Math.floor(Math.random() *users.length)].login))
}
    });
  });
}).catch(err => console.error(err));
</script>

Currently it does return random login names from that file, however, I wish to only randomly select 8 users from this list. My attempt at doing so can be seen in the for loop i < 8 however it prints alot more than 8(240 to be exact)

How can I have it so just returns 8 randomly? say for example

ezmobius
mojodna
kevwil
wayneeseguin
railsjitsu
bmizerany
atmos
fanvsfan

CodePudding user response:

please, remove useless loop, i have commented out users.forEach(function(user){

fetch('https://api.github.com/users').then(function(response) {
 
    response.json().then(function(users){
    document.write("Highlighred Github users")
//     users.forEach(function(user){ 

for (let i=0; i< 8; i  ) {
   document.write('<br>')
   document.write((users[Math.floor(Math.random() *users.length)].login))
}
    });
//   });
}).catch(err => console.error(err));

  • Related