Skip to content
Related Articles

Related Articles

Improve Article

Lodash _.compact() Function

  • Last Updated : 07 Aug, 2020

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.




    // 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 _.comapct() function.




    // 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.




    // 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.




    // 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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :