Array filters

Array filters manipulate arrays. Because an array is a collection of values that are stored in a sequence, you can use an array filter to output certain values from that sequence. You can also add characters to separate items in an array (like putting commas in a list) and remove duplicates or nil values from an array. Used in combination with other array filters or tags, you can also combine arrays (and create new ones!) based on criteria you create. 

Let’s use the join array filter to make a “new product” list look nicer by adding a comma and a space between each item on the list. Here’s how it looks:

Code (key and filter)Even old dogs can learn new tricks with our newest senior pet helpers. Check out the latest: {{ new_products.senior_pets | join: ‘, ‘ }} 
Output Even old dogs can learn new tricks with our newest senior pet helpers. Check out the latest: bowl elevator, stair steps, carry sling, senior vitamins

Practice problem: array filters

We’ll wrap up our practice session with array filters. Here’s the copy we’re going for:

The hottest new product for senior dogs is our ____. Choose from  _____ new products!

The key that contains the value is new_products.senior_pets, and there are 15 items within that array. Use the first filter to output the first item in the array in the first blank. Use the size filter to output the number of items in the array in the second blank.

Select the right Liquid code from the options below:

  1. The hottest new product for senior dogs is our {{ new_products.senior_pets | size}}. Choose from {{ new_products.senior_pets | first }} new products!
  2. The hottest new product for senior dogs is our {% new_products.senior_pets | first %}. Choose from {{ new_products.senior_pets | size }} new products!
  3. The hottest new product for senior dogs is our {{ new_products.senior_pets | “first” }}. Choose from {{ new_products.senior_pets | “size” }} new products!
  4. The hottest new product for senior dogs is our {{ new_products.senior_pets | first }}. Choose from {{ new_products.senior_pets | size }} new products!

The correct answer is D!

Let’s run the code: 

Code (key and filter)The hottest new product for senior dogs is our {{ new_products.senior_pets | first }}. Choose from {{ new_products.senior_pets | size }} new products!
Output The hottest new product for senior dogs is our Stay Snug Bed Warmer. Choose from 15 new products!

Why don’t the other options work?

a. The filters are in reverse order. The copy would come out like this: “The hottest new product for senior dogs is our 15. Choose from Stay Snug Bed Warmer new products!

b. This code uses pairs of percentage signs and curly braces instead of double curly braces.

c. The filters are enclosed in double quotes; they should not be.

Liquid filters offer a huge amount of flexibility in how you can display values in email! Now lets explore even more ways to play in Module 5: Intermediate tags.