Lodash _.compact() Function
Lodash proves to be much useful when working with arrays, strings, objects etc. It makes math operations and function paradigm much easier, concise. The _.compact() function is used to creates an array with all falsey values removed in JavaScript.
Syntax:
_.compact(array)
Parameters: This function accepts only a single parameter as mentioned above and described below:
- array: It is an array to be compacted.
Note: The values false, null, 0, “”, undefined, and NaN are falsey.
Return Value: This function returns the array after filtering the values.
Few examples are given below for a better understanding of the function.
Example 1: Passing a list of both the true and the false elements to _.compact() function.
javascript
// Requiring the lodash library let lodash = require( "lodash" ); // Original array to be compacted let array = [0, 1, false , 2, '' , 3]; let newArray = lodash.compact(array); console.log( "Before compact: " + array); // Printing newArray console.log( "After compact: " + newArray); |
Output:
Example 2: Passing a list containing all the false values to the _.compact() function.
javascript
// Requiring the lodash library let lodash = require( "lodash" ); // Original array to be compacted let array = [0, false , '' , undefined, NaN]; let newArray = lodash.compact(array); console.log( "Before compact: " + array); // Printing newArray console.log( "After compact: " + newArray); |
Output:
Example 3: Passing a list which contains a false element in ” to _.compact() function.
javascript
// Requiring the lodash library let lodash = require( "lodash" ); // Original array to be compacted let array = [ false , 'HTML' , NaN, 'CSS' , 'undefined' ]; let newArray = lodash.compact(array); console.log( "Before compact: " + array); // Printing newArray console.log( "After compact: " + newArray); |
Output:
Example 4: Passing a list containing modified false values to the _.reduce() function.
javascript
// Requiring the lodash library let lodash = require( "lodash" ); // Original array to be compacted let array = [ false , true , 'yes' , 'no' , "no2" ]; let newArray = lodash.compact(array); console.log( "Before compact: " + array); // Printing newArray console.log( "After compact: " + newArray); |
Output:
Please Login to comment...