uniq¶
The 'uniq' filter is designed to remove duplicate elements from an array . It returns a new array containing only the unique elements, preserving their original order.
Functionality
- Arrays: Takes an array as input and returns a new array with duplicate elements removed.
- Uniqueness: Considers elements unique based on their values, not their object identity.
Syntax
ArgumentsThe uniq filter does not require any arguments.
Code Samples
Example 1: Removing Duplicates from an Array
Output:
Example 2: Removing Duplicates from an Array of Strings Output: Example 3: Removing Duplicates from an Array of Objects {% assign products = [{ "name": "Product A" }, { "name": "Product B" }, { "name": "Product A" }] %}
{% assign unique_products = products | uniq %}
{{ unique_products | map: "name" }}
Output:
Outliers and Special Cases¶
- Empty Arrays: If the input array is empty, the
uniqfilter returns an empty array. - Non-Array Input: If the input is not an array, the
uniqfilter returns the original input value unchanged.
Key Points¶
- The
uniqfilter is a handy tool for cleaning and deduplicating data within arrays. - It is essential when you need to ensure that each element in an array appears only once.
- For arrays of objects, consider using the
mapfilter in conjunction withuniqif you want to compare objects based on a specific property.