Skip to content

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

    {{ array_variable | uniq }}
Arguments

The uniq filter does not require any arguments.

Code Samples

Example 1: Removing Duplicates from an Array

    {% assign numbers = [1, 2, 2, 3, 4, 4, 4] %}

    {{ numbers | uniq }} 

Output:

[1, 2, 3, 4]
Example 2: Removing Duplicates from an Array of Strings
    {% assign fruits = ["apple", "banana", "apple", "orange"] %}

    {{ fruits | uniq }} 
Output:
["apple", "banana", "orange"]
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:

["Product A", "Product B"]

Outliers and Special Cases

  • Empty Arrays: If the input array is empty, the uniq filter returns an empty array.
  • Non-Array Input: If the input is not an array, the uniq filter returns the original input value unchanged.

Key Points

  • The uniq filter 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 map filter in conjunction with uniq if you want to compare objects based on a specific property.