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

425
Visualizações
My Code should remove all false values but it is not?

My Code should remove the false values but it is only removing first false value in a given array

const arr = [7, "ate", "", false, 9]



function bouncer(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (!arr[i]) {
      arr.splice(i, 1)
    }
  }
  return arr;
}

console.log(bouncer(arr))

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

0

Why don't use filter like:

const arr = [false,7, "ate", "", false, 9];
console.log(arr.filter(el => el !== false));

Reference:

  • Array.prototype.filter()
about 4 years ago · Juan Pablo Isaza Relatório

0

You can't iterate upwards AND shorten your array like this; splice has the side effect of modifying the original array.

Consider what happens in the case [false, false, true]

  1. i = 0, length = 3, arr = [(false), false, true] -> arr becomes [false, true]
  2. i = 1, length = 2, arr = [false, (true)]-> arr stays [false, true]

(parenthesis denotes current target)

Solutions:

  • Iterate down, not up

    for (let i = arr.length - 1; i >= 0; --i) if (!arr[i]) arr.splice(i, 1);
    
  • Use Array.prototype.filter instead (this will also improve readability)

    arr = arr.filter((item) => !!item);
    
about 4 years ago · Juan Pablo Isaza Relatório

0

The .filter() approach as suggested by Rossaini or PaulS is definitely a better path to follow. However, your approach works if you work through the array backwards:

const test=[7, "ate", "", false, 9];

function bouncer(arr) {
  if (!arr.length) return [];
  for (let i=arr.length-1; i--;){
    if(!arr[i]){
        arr.splice(i, 1)
      }
  }
  return arr;
}

console.log(bouncer(test));
console.log(bouncer([]));
// solution with filter:
console.log(test.filter(e=>e));

You need to consider that .splice() actually changes the source array you are working on. Using an increasing index i you will skip an entry each time an element is deleted from the array. By walking through the array backwards (from the end to the beginning) as done with for (let i=arr.length; i--;) you will avoid this problem.

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