Non-tech founder’s guide to choosing the right software development partner Download Ebook
Home>Blog>Zip two arrays repeating values of the smaller one

Zip two arrays repeating values of the smaller one

So, we have two arrays and we need map each element of the first array to an element from the second. The length of the second array may be less or equal than the first one. What’s if we need to repeat values of the smaller one?

For example, there are two arrays:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8]

const letters = ['a', 'b', 'c']



And we need to get something like:


[ { number: 1, letter: 'a' },

  { number: 2, letter: 'b' },

  { number: 3, letter: 'c' },

  { number: 4, letter: 'a' },

  { number: 5, letter: 'b' },

  { number: 6, letter: 'c' },

  { number: 7, letter: 'a' },

  { number: 8, letter: 'b' } ]

You can use Google or your math skills 😎 and finally will come to this:


const getNormalizedIndex = (index, array) => ((index + array.length) % array.length) % array.length



const numbers_letters = numbers.map((item, index) => {

  return {

    number: item,

    letter: letters[getNormalizedIndex(index, letters)]

  }

})

Run it and you’ll get the expected result.

Discover More Reads

Recent Projects

We take pride in creating applications that drive growth and evolution, from niche startups to international companies.

Do you have a tech idea?

Let’s talk!

By submitting this form, you agree with JetRockets’ Privacy Policy

If you prefer email, write to us at hello@jetrockets.com