Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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



>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// remove truthy values
var removeTruthy = function (arr) {
    return arr.filter(val => !val)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading