0

I was using Myjson.slice(1, 20). I need only 20 items from Myjson which has a length of 2624 and in this code I tried to you slice like this but I don't know what to do to make the difference between xxx and yyy to 20:

  let xxx = Math.floor(Math.random() * 2624 + 1);
  let yyy = Math.floor(Math.random() * 2624 + 1);

  {Myjson.slice(xxx, yyy).map((item) => (
    <Link
      href={item.ud}
      key={item.id}
    >
     {item.test}
    </Link>
  ))}

How can I get 20 random items from this JSON?

frg
  • 45
  • 3
  • 1
    [Shuffle the array](https://stackoverflow.com/questions/59810241/how-to-fisher-yates-shuffle-a-javascript-array) and then grab the first 20. – Andy Mar 27 '23 at 17:58

2 Answers2

1

In the first step, you can find 20 random indexes. Then create an array of items with these indexes. And finally, render 20 items.

    const indexes = [];

    while (indexes.length < 20) {
      const index = Math.floor(Math.random() * 2624);
      if (!indexes.includes(index)) {
        indexes.push(index);
      }
    }

    const items = indexes.map((index) => myJson[index]);

    items.map((item) => (
      <Link 
         href={item.ud}
         key={item.id}> 
        {item.test}
      </Link>
    ));
Andrew
  • 630
  • 1
  • 5
  • 14
1

The solution is simple.

Edited 1: Correction for Fisher-Yates shuffle

// Assume that Myjson.constructor.name === Array.name

// Fisher-Yates Shuffle (in-place)
const a = Myjson;
for (let i = a.length; i-- > 0;) {
  const j = Math.floor(Math.random() * i); // 0 ≤ j ≤ i
  [a[i], a[j]] = [a[j], a[i]];
}

{Myjson
  .slice(0, 20)
  .map((item) => (
    <Link
      href={item.ud}
      key={item.id}
    >
     {item.test}
    </Link>
  ))}