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

146
Visualizações
Javascript for loop returning empty array

I have a for loop

for (let i = 0; i < itemsArray.length; i++) {
  newItemsArray.push(itemsArray[i])
}

when I console log newItemsArray I get same as itemsArray. However if I do something like this, I get empty array with undefined values

for (let i = 0; i < 5; i++) {
  newItemsArray.push(itemsArray[i])
}

I am trying to add certain number of items on page load so 5 items until we see 5th item then add another 5. If there is a better solution, please suggest :)

Thanks

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

0

You can do this without a loop:

const starterItems = ["apple", "banana", "cherry", "mango", "orange"]
let newItems = [...starterItems]
// if you want to add extra 5 items:
newItems = [...newItems, ...starterItems]

This is ES6 feature, you can read more about it here: Spread Operator on MDN

Edit: If you want to get a portion of your array, you can use filter method like so:

let itemsLimit = 5
newItemsArray = itemsArray.filter((item, index) => index < itemsLimit)
// later in the code you can change itemsLimit, 
// and then you need to filter the array again
itemsLimit = 10
newItemsArray = itemsArray.filter((item, index) => index < itemsLimit)

The code above will include every array item until itemsLimit is "reached" by items' index This will create array you wanted. If you want to include starter position too, you can do it like this:

let starterPosition = 3
newItemsArray = itemsArray.filter((item, index) => index < itemsLimit && index >= starterPosition)

More on filter feature of Arrays in Javascript: Filter Array method on MDN

about 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