0

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;
 }
  



la10nay
  • 35
  • 3

2 Answers2

0

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)
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26
0
// remove truthy values
var removeTruthy = function (arr) {
    return arr.filter(val => !val)
}
  • thank you! this worked...does the "val" = truthy and the "!val" = falsy?... I'm confused on that part – la10nay Apr 06 '23 at 17:44
  • 1
    **filter(callback)** method applies a callback function to each element of the original array, and creates a new array that contains only the elements for which the callback function returns true. To filter out truthy values, we need to take the not(!) logic. eg: if val=true then condition (!val) become false. Therefore, it won't be included in the new array. – Namal Sanjaya Apr 06 '23 at 18:03