Home > Enterprise >  Get random values from array and post in DOM
Get random values from array and post in DOM

Time:11-13

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
];

CodePudding user response:

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;
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

i dont know what exactly know you mean but theres Math.floor(math.random())) if that helps you.

  • Related