1

Why is the if condition failing? Take the array, filter out every item and where the item is strictly equal to null, then splice the element at that particular index to remove one item which is null. But it keeps one null in the array. Why is this happening?

  let a = [null, null, null, "a"];

  a.filter(function(v,i){
    if (v===null){
        a.splice(i, 1)
    }
      console.log(a);// gives [null, "a"]
  })
Deke
  • 4,451
  • 4
  • 44
  • 65
  • 1
    because the array gets shorter when you splice it - but the index keeps going up in every iteration ... so, if you have two nulls in a row ... you miss one - if you want to use splice, your best bet is to use a regular `for` loop - and best done in reverse - if you're keen on using an array method, you can always (ab)use reduceRight – Jaromanda X Jul 25 '22 at 09:43
  • 1
    1. You're not using `.filter()` correctly at all. It's not just a tool for iteration. 2. If you're traversing the array *forwards* and remove an elements, all the subsequent elements shift their position one back. So if you remove the item at index 0, then index 1 becomes the new index 0. And then `.filter()` continues with the next item - index 1 which is the former index 2. Thus skipping the former index 1. – VLAZ Jul 25 '22 at 09:44
  • As others are saying... You need to compensate for the removed elements by subtracting from i the number of times you spliced the array: a.splice(i-comp,1); comp++; This should work I think. – digitalniweb Jul 25 '22 at 09:46
  • if you're going to "abuse" an array method, "abuse" one that is more fit for purpose `a.reduceRight(function (_, v, i) { if (v === null) { a.splice(i, 1); }}, null);` - I feel dirty posting that – Jaromanda X Jul 25 '22 at 09:50
  • @digitalniweb there is no reason to "compensate" in a `.filter()`. Either use the method *properly* with `return v === null` which does all the work, or use a regular loop where you have more fine control over the iteration. – VLAZ Jul 25 '22 at 09:51
  • I mean, you may as well have mis-used `.filter` ... since you don't care what is returned – Jaromanda X Jul 25 '22 at 09:52
  • @VLAZ I thought it was foreach loop. But it might still work. And I didn't mean he should use it that way, I was just proposing the fastest solution to this scenario, not the best one. I'd use simple for loop for this. – digitalniweb Jul 25 '22 at 10:04

0 Answers0