Good day.

I want to know how to remove all false elements from an array in js, the problem is that something goes wrong on the false element. Quite already confused. ( Tell me please.

function bouncer(arr) { for(var i = 0; i < arr.length; i++) { if (!(arr[i])) { arr.splice(i, 1); } } return arr; } console.log(bouncer([7, 'ate', '', false, 9])); 

    3 answers 3

    Remove in the opposite direction. And everything will work. Somewhere like this:

     function bouncer(arr) { for(var i = arr.length-1; i>= 0; i--) { if (!(arr[i])) { arr.splice(i, 1); } } return arr; } console.log(bouncer([7, 'ate', '', false, 9])); 

    Or use the filter function.

    • Thank you works, but do not tell me why? About the filter did not know convenient. - Stee1House
    • It came, thanks) - Stee1House

    But you can make everything much easier :) The same educational task and the standard typeof function easily finds everything false:

     function bouncer(arr) { for(var i = 0; i < arr.length; i++) { if (typeof(arr[i]) == "boolean") { arr.splice(i, 1); } } return arr; } console.log(bouncer([7, 'ate', '', false, true, 9])); 

    Added true to the example so that no one would doubt that there are only false

      !(arr[i]) should, in theory, equally give true if there is '', 0, false, undefined, etc.

      Use !(arr[i]===false)

      up:
      And even if you delete an element, you must i-- , otherwise the next element will be skipped.

      • It will not work, I tried it already ( - Stee1House
      • And here is the explanation) Thank you very much) - Stee1House