0

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
];
Bryce Steuer
  • 456
  • 1
  • 4
  • 15
  • does this answer you question https://stackoverflow.com/questions/4550505/getting-a-random-value-from-a-javascript-array – Faizal Hussain Nov 11 '21 at 19:20
  • Take N random elements from an array has several answers on StackOverflow. The second problem of "posting HTML via DOM" depends on what format you want to give them. Once again, there are many ways you can find on SO. – Balastrong Nov 11 '21 at 19:21
  • I have already tried that solution Faizal. Balastrong I have spent a few hours already trying to find the right solutions to my exact situation. Found some close but a missing piece was too big to fit my case exactly, and I'm not super experienced enough to do it myself. – Bryce Steuer Nov 11 '21 at 19:23

1 Answers1

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.

MartinJ
  • 23
  • 4