How to return a new array with all truthy values removed? (Javascript)

190 views Asked by At

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

There are 2 answers

2
Namal Sanjaya On BEST ANSWER
// remove truthy values
var removeTruthy = function (arr) {
    return arr.filter(val => !val)
}
0
ProfDFrancis On

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)