Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. /** Filter false values off an Array.
  2. * Why it works, simply `filter` evaluates the return of the iterator function to a boolean
  3. * if the value is true will return the current item and the opposite for false.
  4. * Misunderstanding happens when you think you will have to explictly return a boolean like
  5. * `return currentItem === 'someValue' ` but actually if you returned any value it will be converted to a boolean
  6. * just like doing `!!currentItem`
  7. * so you can have a shorter version of filtering like below
  8. **/
  9. var a = [0, 1, 2, 3, 'amin', '', false, NaN]
  10.  
  11. a.filter(x => x); // [1, 2, 3, "ate"]
  12. a.filter(x => !x); // [0, "", false, NaN]
  13.  
  14. // or that way
  15. a.filter(function(x){
  16. return x;
  17. });
  18.  
  19. /* Using lodash
  20. * _.identity is a no-op function which just returns what is passed to it
  21. */
  22. _.filter(a, _.identity); // [1, 2, 3, "ate"]
  23. _.compact(a) // or just that simply.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement