-1

Im trying to use a javascript function I have made to iterate over an array.My function looks like this and it works:

const shuffleAndPick = (array, amount) => {
    return array.sort(() => 0.5 - Math.random()).slice(0, amount);
  };

The thing is that I want it to iterate over an array and pick certain things like, ${image} ${name} etc.

Something like this (but only for the objects that my function randomly selects, as this example would iterate over the whole array):

{images.map((images) => (
        <div className="key" key={images.id}>
        <h3>{images.name}</h3>
        <h3>{images.sanskritname}</h3>
        <p>{images.description}</p>
        <img src={images.image} alt={images.name} />
        </div> 
      ))} 

Do I need to use my function with a map() for my purpose? And how would I write the correct syntax for that that if I want to write it in es6?

Thanks

camillalofroth
  • 179
  • 1
  • 1
  • 10

2 Answers2

1

As I understand you can do:

{shuffleAndPick(images, 3).map((image) => (
        <div className="key" key={image.id}>
        <h3>{image.name}</h3>
        <h3>{image.sanskritname}</h3>
        <p>{image.description}</p>
        <img src={image.image} alt={image.name} />
        </div> 
      ))}
strdr4605
  • 3,796
  • 2
  • 16
  • 26
  • Thank you both! :) It is something like that I want to acheive. But none of the examples are working. Are there any difference if the array consists in object or not? I am pretty new to this and It could be more accurate to say that I am using props. – camillalofroth Mar 14 '20 at 11:03
1

You can just do this. This will help you to obtain the desired results. (Expected that you have an array of Objects!).

{shuffleAndPick(images, amount).map((image) => (
    <div className="key" key={images.id}>
    <h3>{images.name}</h3>
    <h3>{images.sanskritname}</h3>
    <p>{images.description}</p>
    <img src={images.image} alt={images.name} />
    </div> 
  ))}
Anglesvar
  • 1,132
  • 8
  • 15