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

142
Visualizações
The splice method causes the for loop to be executed n - 2 times (n is the number of elements in an array)

I want to remove the elements of an array with n elements using a for loop and the splice method one by one. The loop is executed n - 2 times and there will be 2 elements inside the array at the end. Why is that so?

const fruits = ['Apple', 'Orange', 'Watermelon', 'Peach']

for(index in fruits){
    console.log('Execution Number:', index);
    console.log('Before:', fruits);
    fruits.splice(0, 1);
    console.log('After:', fruits);
    console.log('-'.repeat(50));
}

console.log('\nFinal Result:', fruits)

result:

Execution Number: 0
Before: [ 'Apple', 'Orange', 'Watermelon', 'Peach' ]
After: [ 'Orange', 'Watermelon', 'Peach' ]
--------------------------------------------------
Execution Number: 1
Before: [ 'Orange', 'Watermelon', 'Peach' ]
After: [ 'Watermelon', 'Peach' ]
--------------------------------------------------

Final Result: [ 'Watermelon', 'Peach' ]

I know that I can do this with a single line of code using the splice method but I wanted to test if I can do this using a for loop.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This happen because you are reducing the length of the array in every loop. By doing this, the number of element in the array decrease but the index still increment.

Fruits Index
['Apple', 'Orange', 'Watermelon', 'Peach'] 0 0 < 4 so, Apple is deleted
['Orange', 'Watermelon', 'Peach'] 1 1 < 3 so, Orange is deleted
['Watermelon', 'Peach'] 2 2 < 2 Here 2 < 2 is false, the loop stops

A solution would be to do a for loop with a fixed length calculated before the loop

const fruits = ['Apple', 'Orange', 'Watermelon', 'Peach']
const length = fruits.length
for (let index = 0; index < length; index++){
    console.log('Execution Number:', index);
    console.log('Before:', fruits);
    fruits.splice(0, 1);
    console.log('After:', fruits);
    console.log('-'.repeat(50));
}

console.log('\nFinal Result:', fruits)

As @reyno was mentioning, in the above snippets you can't access fruits individually. In fact if you want to access each fruit in the foor loop you can do this by accessing to the first element of the array each time : fruits[0]

about 4 years ago · Juan Pablo Isaza Relatório

0

The issue is being seen because the length of the array is decreased by one in each iteration due to fruits.splice(0,1).

  1. Iteration 1 - index = 0; fruits.length = 4
  2. Iteration 2 - index = 1; fruits.length = 3
  3. Iteration 3 - index = 2; fruits.length = 2 -> for loop breaks

Hence, the observation.

about 4 years ago · Juan Pablo Isaza Relatório

0

When you do fruits.splice you are modifying the array used for the for loop itself. If you look at index, it is incrementing in each loop. After Execution Number: 1, it increments to 2 and looks at fruits and sees there is no more elements. Seeing that, it exits the for loop.

If you want to do it with a for loop, what you probably wanted was

const fruits = ['Apple', 'Orange', 'Watermelon', 'Peach']

const fruitsLen = fruits.length;
for(let i = 0; i < fruitsLen; i++){
    console.log('Execution Number:', i);
    console.log('Before:', fruits);
    fruits.splice(0, 1);
    console.log('After:', fruits);
    console.log('-'.repeat(50));
}

console.log('\nFinal Result:', fruits)
about 4 years ago · Juan Pablo Isaza 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