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

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

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 Report

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 Report

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 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!