skip to Main Content

I have a JSON file with data in it that I’m trying to map out.

 const randomCategories = []

  for (let i = 0; i < 10; i++) {
    const randomIndex = Math.floor(Math.random() * categoryData.length)
    const randomCategory = categoryData[randomIndex]
    console.log(randomCategory)
    randomCategories.push(randomCategory)
  }

I only want 10 items from the categoryData array without any duplicates. I cannot get anything to work that removes duplicates or doesn’t include them to begin with.

There’s a second array as well:

  const colors = [
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(139,0,0)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(0,0,139)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(184,134,11)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(0,100,0)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(0,139,139)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(139,0,139)"
    },
    {
      "gradient-start": "rgba(0,0,0,0)",
      "gredient-end": "rgb(233,140,0)"
    }
  ]

Colors does not need to be randomized, it’s fine in the order it is in.

From there, I’m mapping out items from randomCategories into a grid of components for the data

 <div className="grid grid-rows-1 grid-flow-col w-[2360px] h-[233px] max-h-[233px] gap-x-3">
      {randomCategories.map((item) => (
        <CategoryCard key={item?.id} name={item?.name} image={item?.image} />
      ))}

    </div>

The idea is that I’ll generate an array of 10 random, unique items from categoryData and display those 10 items in 10 CategoryCards. Each CategoryCard should have a color from the colors array in it, in the same order. So if it’s red, green, blue, yellow, etc. once I reach the end of the colors array it repeats again; red, green, blue, yellow, etc. I’m not sure how to include the colors in the .map function or how I’d go about having that array repeat?

Attached picture is what I’m trying to accomplish:

This is what I'm going for

3

Answers


  1. What if you do a uniqueness check before adding each category, and then constrain the loop by the size of the array rather than the number of iterations?

      const randomCategories = [];
    
      while (randomCategories.length < 10) {
        const randomIndex = Math.floor(Math.random() * categoryData.length);
        const randomCategory = categoryData[randomIndex];
        if (randomCategories.indexOf(randomCategory) !== -1) {
          console.log(randomCategory);
          randomCategories.push(randomCategory);
        }
      }
    
    Login or Signup to reply.
  2. Replace the for loop with a while loop, then only add the items that you haven’t already extracted:

      const randomCategories = []
    
      let i = 0;
      while (randomCategories.length < 10) {
        const randomIndex = Math.floor(Math.random() * categoryData.length)
        const randomCategory = categoryData[randomIndex]
        console.log(randomCategory)
        if (!randomCategories.find(el => el['gradient-start'] === randomCategory['gradient-start'] && el['gradient-end'] === randomCategory['gradient-end']) {
          randomCategories.push(randomCategory)
        }
      }
    
    Login or Signup to reply.
  3. Get random categories with Array#splice:

    const categoryData = 'music software football books media health training sports nature science space biology evolution games programming'.match(/S+/g);
    const copy = categoryData.slice();
    const randomCategories = Array.from({length:10}, (_, i) => copy.splice(Math.random() * copy.length | 0, 1)[0]);
    randomCategories.forEach((c, i) => console.log(i+1, c));
    .as-console-wrapper{max-height:100%!important}

    Then use a category index to pick a color (the colors could be randomized the same way as the categories):

    <div className="grid grid-rows-1 grid-flow-col w-[2360px] h-[233px] max-h-[233px] gap-x-3">
          {randomCategories.map((item, i) => (
            // use colors[i] to pick a color and insert into the card's style
            // or pass the index to a card so it could select a color itself
            <CategoryCard key={item?.id} name={item?.name} image={item?.image} />
          ))}
    
        </div>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search