Antisocial Dev
Antisocial Dev

Reputation: 11

How to pop all elements from an array

var arr = [0,1,2,2,3,4,5,5,6];

for(let i = 0; i < arr.length; i++) {
    let item = arr.pop()
    console.log(item)
}
//Returns 6, 5, 5, 4, 3

I have no idea why this is returning only the numbers given instead of every number in the array. Any help would be greatly appreciated.

Upvotes: 0

Views: 3275

Answers (3)

Saadi Toumi Fouad
Saadi Toumi Fouad

Reputation: 2829

You need to reverse your iteration, becuase .pop method removes the last item so when iterating from 0 to last item you will not find all of them :)

var arr = [0,1,2,2,3,4,5,5,6];

for(let i = arr.length; i > 0; i--) {
    let item = arr.pop()
    console.log(item)
}

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

Based on the documentation .pop() returns:

The removed element from the array; undefined if the array is empty.

So technically on each iteration the code removes the last element from the array which changes the .length property.

Probably a good representation what happens with the extended index from the loop:

var arr = [0,1,2,2,3,4,5,5,6];

for(let i = 0; i < arr.length; i++) {
    let item = arr.pop()
    console.log({i, item, length: arr.length});
}

All together for loop was running the block five times which represents the last five elements from your array if you read the array from the back. That's why you have 6,5,5,4,3 as an output.

I hope this clarifies!

Upvotes: 1

J&#243;zef Podlecki
J&#243;zef Podlecki

Reputation: 11283

Can you change for to while loop? You would then console log all items

while(arr.length) {
    let item = arr.pop()
    console.log(item)
}

Upvotes: 1

Related Questions