Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!