Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
How to iterate through an array which contain less than the iterator value

the title is bit confusing so sorry about that, so what i have is a too arrays one of the array contain more then the second array

   x = [1,2,3,4,5];
    y =  [{
          x: "test1",
          y: "test2",
          z: "test3",
          w: `test4`
        }] 

so what I want to do is for example

 for (let i = 0; i < x.length; i++) {
     console.log(y[i])
}

which would only log out the first one one time but what i want is to log y as many as x length hope that was clear enough

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use the remainder operator to get the corresponding item from the shorter array:

const x = [1, 2, 3, 4, 5];
const y = [{"x":"test1","y":"test2","z":"test3","w":"test4"},{"x":"test21","y":"test22","z":"test23","w":"test24"}]

for (let i = 0; i < x.length; i++) {
  const idx = i % y.length;
  console.log(y[idx])
}

Or you can use the last index of the y array, if the current i value is over the length of the last item index in the y array:

const x = [1, 2, 3, 4, 5];
const y = [{"x":"test1","y":"test2","z":"test3","w":"test4"},{"x":"test21","y":"test22","z":"test23","w":"test24"}]

for (let i = 0; i < x.length; i++) {
  const idx = Math.min(i, y.length - 1)
  console.log(y[idx])
}

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda