skip to Main Content

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?

2

Answers


  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>
        ));
    
    Login or Signup to reply.
  2. 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>
      ))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search