Count number of consecutive years in category array I need to count the number of consecutive years a user has been a member of our organization. For example, if they've been a member from in 2018, 2019, 2020 and 2021, their loyalty will be 4 years.
If they've been a member in 2018, 2019 and 2021, their loyalty will be 1 year (they missed 2020.)
I'm currently using Categories to assign a year to Users in Craft to do the assignment of a year to a person.
Hope that makes sense. I would very much appreciate some help on how to tackle it!
If you don't want to build a custom plugin, this would be a good time to use Twig's reduce filter, which takes a set of values and iterates over them to output a single value based on supplied logic.
Using Andy's answer as the basis might look like this (untested):
{% set currentYear = now|date('Y') %}

{% set loyaltyScore = currentUser.years.all()|reduce(
    (score, year) =&gt; 
        score == 0 and year == currentYear or 
        score &gt; 0 and year == currentYear - 1 ?
        score + 1,
        0
) %}

I'm assuming your data is already in the right order if it's a category group.