how to use the compact function from lodash in javascript

The compact function from Lodash is used to remove all falsey values from an array. Falsey values in JavaScript are false, null, undefined, 0, -0, NaN, and an empty string ("").

The syntax for using compact function in JavaScript is as follows:

index.tsx
_.compact(array)
17 chars
2 lines

Here, array is the array from which you want to remove falsey values.

Example:

index.tsx
const _ = require('lodash');

const array = [0, 1, false, 2, '', 3, undefined, NaN, 4, null];

const compactArray = _.compact(array);

console.log(compactArray); // Output: [ 1, 2, 3, 4 ]
188 chars
8 lines

In the above example, we have used the compact function from Lodash to remove all the falsey values from the array and stored the result in the compactArray. The output of this code is [ 1, 2, 3, 4 ] where all the falsey values (0, false, '', undefined, NaN, and null) are removed from the original array.

gistlibby LogSnag