Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
Get random values from array and post in DOM

I spent a long time looking how to get random values from both objects and arrays, but I can't seem to discern how to pull this off. I have this code, which will house up to a hundred different reviews with credentials corresponding. How can I a) Pull a random set of four reviews with all corresponding data every time the page refreshes (must be unique) b) Post those reviews in HTML/CSS via DOM

Here's the base code:

var reviews = [
{
 content: "content of review", // no need to have html there even.
 by: "name of reviewer or initials",
 stars: 5, // default, no need to specify to every item
 source: "Google Play",  // default, no need to specify to every item
},
{
 content: "content of review", // no need to have html there even.
 by: "name of reviewer or initials",
 stars: 5, // default, no need to specify to every item
 source: "Google Play",  // default, no need to specify to every item
},
etc.etc
];
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

First thing that comes to my mind is having a function which returns an array of n unique elements (in your case, n = 4)

const randomElementsFromArray = (amountOfElements, array) => {
  const arrayWithSelectedElements = [];
  while (arrayWithSelectedElements.length !== amountOfElements) {
    const randomIndex = Math.floor(Math.random() * array.length);
    const chosenElement = array[randomIndex];
    if (!arrayWithSelectedElements.includes(chosenElement)) {
      arrayWithSelectedElements.push(chosenElement);
    }
  }

  return arrayWithSelectedElements;
};

It takes the amount of elements you want to choose and the array you want it to choose from.

One drawback would be the fact that the number of times the loop runs is not consistent, but it should do the trick.

EDIT: Shoot, I forgot that there is a second part to the question.

If you aren't using any JS framework such as React, and you want to do it in pure JS, you would create another function which loops over the elements from the array returned by randomElementsFromArray (or use .map method on the returned array) and creates elements, their content, and adds them to the DOM.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!