Home > Back-end >  Javascript for loop returning empty array
Javascript for loop returning empty array

Time:07-25

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

CodePudding user response:

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

  • Related