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 CategoryCard
s. 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:
3
Answers
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?
Replace the for loop with a while loop, then only add the items that you haven’t already extracted:
Get random categories with
Array#splice
:Then use a category index to pick a color (the colors could be randomized the same way as the categories):