Skip to content

reverse

The 'reverse' filter is designed to reverse the order of elements in an array or characters in a string.

Functionality

  • Arrays: Takes an array as input and returns a new array with the elements in reverse order.
  • Strings: Takes a string as input and returns a new array where each element is a character of the original string in reverse order.

Syntax

    {{ array_variable | reverse }}
or
    {{ string_variable | reverse }}

Arguments

This filter does not require any arguments.

Code Samples

Example 1: Reversing an Array

    {% assign numbers = [1, 2, 3, 4] %}
    {{ numbers | reverse }}
Output:
[4, 3, 2, 1]
Example 2: Reversing a String (Returning an Array)
    {% assign message = "Hello" %}
    {{ message | reverse }}

Output:

["o","l","l","e","H"]
Example 3: Reversing a String and Joining Back into a String
    {% assign message = "Hello" %}
    {{ message | reverse | join:'' }}
Output:
olleH

Outliers and Special Cases

  • Empty Arrays/Strings: If the input array or string is empty, the reverse filter returns an empty array.
  • Non-Array/String Input: If the input is not an array or string, the reverse filter returns the original input value unchanged.

Key Points

  • The reverse filter is useful for manipulating the order of elements in arrays and characters in strings.
  • For strings, it returns an array of characters by default. If you want a reversed string, you can use the join filter to combine the characters back into a string after reversing.
  • It does not modify the original array or string; it creates a new one with the reversed order.