Skip to content

compact

The compact filter is designed to remove nil (null or empty) values from arrays. This can be particularly useful when working with dynamically generated arrays that might contain empty slots or undefined elements.

Functionality

  • Arrays: Takes an array as input.
  • Nil Removal: Filters out any elements within the array that are considered nil, which includes:
    • null values
    • Empty strings ("")
    • Empty arrays ([])
    • Empty objects ({})
  • Output: Returns a new array containing only the non-nil elements from the original array.

Syntax

    {{ array_variable | compact }}

Arguments

The compact filter does not require any arguments.

Code Samples

Example 1: Removing Null Values

    {% assign data = ["apple", null, "banana", null, "orange"] %}

    {{ data | compact }}

Output:

["apple", "banana", "orange"]
Example 2: Removing Empty Strings

    {% assign words = ["hello", "", "world", "", "foo"] %}

    {{ words | compact }}

Output:

["hello", "world", "foo"]
Example 3: Removing Empty Arrays and Objects

    {% assign mixed_array = [1, [], {}, "two", [3, 4]] %}

    {{ mixed_array | compact }}

Output:

[1, "two", [3, 4]]

Outliers and Special Cases

  • Empty Input Array: If the input array is already empty, the compact filter returns an empty array.
  • Non-Array Input: If the input is not an array, the compact filter might return the original input value unchanged or throw an error.

Key Points

  • The compact filter is a handy tool for cleaning up arrays and removing unwanted empty or null values.
  • It is particularly useful when dealing with data that might be incomplete or dynamically generated.
  • The filter creates a new array without modifying the original one.
  • By default, it considers null, empty strings, empty arrays, and empty objects as nil values.