Computer >> Computer tutorials >  >> Programming >> Javascript

How to remove false values from an array in JavaScript?


Javascript library underscore.js has provided _.compact() method to remove all the false values in an array. The false values in an array are nothing but NaN, undefined, empty string, false and 0. It returns a new array that is free from false values as output.

syntax

_.compact( array );

It takes an array as a parameter and returns a  new array that is free from false values.

Example

<html>
<body>
   <script type="text/javascript"    src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
      document.write(_.compact(["zero", 1, NaN,false, 2, '', 3, undefined]));
   </script>
</body>
</html>

Output

zero,1,2,3

In case if any false value is inside a quotation mark(" ") then it won't be treated as a false value.

In the following example, since 0 is present inside quotation marks as "0", it won't be treated as a false value. So it will be displayed in the output.

Example

<html>
<body>
   <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
   <script>
      document.write(_.compact(["0", 1, 'NaN',false, 2, '', 3, undefined]));
   </script>
</body>
</html>

Output

0,1,NaN,2,3