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:nullvalues- Empty strings (
"") - Empty arrays (
[]) - Empty objects (
{})
- Output: Returns a new array containing only the non-nil elements from the original array.
Syntax
Arguments
The compact filter does not require any arguments.
Code Samples
Example 1: Removing Null Values
Output:
Example 2: Removing Empty StringsOutput:
Example 3: Removing Empty Arrays and ObjectsOutput:
Outliers and Special Cases¶
- Empty Input Array: If the input array is already empty, the
compactfilter returns an empty array. - Non-Array Input: If the input is not an array, the
compactfilter might return the original input value unchanged or throw an error.
Key Points¶
- The
compactfilter 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 asnilvalues.