What is the _.compact() method in Lodash?

Overview

The _.compact() method in Lodash is used to create a new array from an existing array by filtering out all the falsy values.

The following values are considered falsy in JavaScript:

  • false
  • 0
  • Empty string
  • undefined
  • null

Syntax


_.compact(array)

Parameters

This method accepts the following parameters:

  • array: This is the array to be compacted.

Return value

This method returns a filtered array.

Example

Let’s look at an example of the _.compact() method in the code snippet below:

Console

Explanation

In the HTML tab:

  • Line 5: We import the lodash script.

In the JavaScript tab:

  • Line 2: We create an array and initialize it with a few values.

  • Line 5: We use the _.compact() method to filter out all the falsy values from the array.

  • Line 8: We print the output to the console.

Output

In the output, we see an array in which all the falsy values are removed.

Free Resources