Categories
JavaScript Answers

How to select 5 random elements with JavaScript?

Spread the love

Sometimes, we want to select 5 random elements with JavaScript.

In this article, we’ll look at how to select 5 random elements with JavaScript.

How to select 5 random elements with JavaScript?

To select 5 random elements with JavaScript, we can spread the elements into an array.

Then we can use the array sort method to shuffle the array.

And we use slice to pick the first 5 items.

For instance, we write:

<ul>
  <li>First</li>
  <li>Second</li>
  <li>Third</li>
  <li>4th</li>
  <li>6th</li>
  <li>7th</li>
  <li>8th</li>
  <li>9th</li>
  <li>10th</li> 
</ul>

to add some li elements.

Then we write:

const els = document.querySelectorAll('li')
const randomElements = [...els]
  .sort(() => {
    return Math.random() - 0.5
  })
  .slice(0, 5)
console.log(randomElements)

to select all the li’s with querySelectorAll.

Then we spread the els into an array.

Next, we call sort on the elements array with a callback that picks a random number that can be positive or negative to shuffle the array.

Then we call slice with 0 and 5 to return the first 5 elements from the shuffled array.

Conclusion

To select 5 random elements with JavaScript, we can spread the elements into an array.

Then we can use the array sort method to shuffle the array.

And we use slice to pick the first 5 items.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *