skip to Main Content

I have two different arrays:

const texts = ['text1', 'text2', 'text3', 'text4']
const images = ['image1', 'image2']

I map over the text and display img corresponding but I always have fewer images.

So I want to transform my images array to display image1 two times and image2 two times:

const images = ['image1', 'image1', 'image2', 'image2']

Data come from an API so I can have a array of text with 9 elements and array of images with 4 elements. I want to always have a perfect repetition:

['image1', 'image1', 'image2', 'image2', 'image3', 'image3', 'image4', 'image4', 'image4']

Here is a minimal example:

const texts = ['text1', 'text2', 'text3', 'text4', 'text5']
const images = ['image1', 'image2']

return texts.map((text, index) => <div>
   {text}
   <img src={images[index]} // NOT work
 </div>))


// Expected images = ['image1', 'image1', 'image2', 'image2', 'image2']

Images should be distributed evenly over the texts, and if there’s an odd number of texts the last image should be included one more time.

Thanks for your help.

2

Answers


  1. You can achieve the expected result by firstly calculating how many items missing from the images then dividing it by the count of them.

    By this you can get how many you need from each.

    Then you just walk trough the array and repeat each item by the number you got before (plus the existing one).

    Lastly we calculate how many is missing and then add the last item again as many times as needed.

    const texts = ['text1', 'text2', 'text3', 'text4', 'text5', 'text6', 'text7'];
    const images = ['image1', 'image2', 'image3'];
    const images_new = [];
    
    var remaining = texts.length - images.length;
    var count = remaining / images.length;
    for (i = 0; i < images.length; i++) {
      for (j = 0; j < Math.floor(count) + 1; j++) {
        images_new.push(images[i]);
      }
    }
    
    var remaining = texts.length - images_new.length;
    for(i=0;i<remaining;i++){
      images_new.push(images_new.slice(-1)[0]);
    }
    
    console.log(images_new);
    Login or Signup to reply.
  2. Simple math. Take the number of text indexes and divide it by the number of images you have. So you know how many groupings. If you have any extra you set it to the last image index.

    const texts = ['text1', 'text2', 'text3', 'text4', 'text5'];
    const images = ['image1', 'image2'];
    
    const num = Math.floor(texts.length / images.length);
    
    const result = texts.map((text, index) => {
      const imageIndex = Math.min(Math.floor(index/num), images.length - 1); 
      return `${text} - ${images[imageIndex]}`;
    });
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search