skip to Main Content

I have seen how to remove falsy values from an array but haven’t found a solution for returning a new array with all truthy elements removed. I attempted to replace falsy values with truthy ones in my "solution" but the results are not leaving me with an array with only falsy values.

      var removeTruthy = function (arr) {
         
          for (var i = 0; i < arr.length; i++) {
       
          if (arr[i] == true  || (arr[i]) == {} || arr[i] == "0" || arr[i] == 5 || arr[i] == Infinity      || arr[i] == "hello") {
              arr.splice(i, 1);
             i--;
         }
        
     }
     return arr;
 }
  



2

Answers


  1. All you need is .filter()

    To filter out all the falsy, .filter(element => element).

    To filter out all the truthy, this:

    const x = [null, 0, 1, 2, 3, undefined, true, {}, "0", 5, Infinity, "hello", [], false, -1]
    
    const y = x.filter(e => !e)
    
    console.log(y)
    Login or Signup to reply.
  2. // remove truthy values
    var removeTruthy = function (arr) {
        return arr.filter(val => !val)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search