Freddy
Freddy

Reputation: 867

Comparing two arrays, checking for matching values

Using HubL (as I'm building a module in HubSpot), I have two arrays:

  1. topics : Which is a list of topics.
  2. all_tags: Which is an array of all the blog tags in the system.

If I dump out these arrays, this is what it will return:

So essentially, {{ topics }} has a tag ("Insight") that doesn't exist in the system yet.

What I'm trying to do is to create a third array, which will contain matching results from the two above arrays. For example, topics_final, once returned, should print [Data, Accounting].

But, when printing {{ topics_final }}, the array is empty.

What I've tried:

<!-- this gets all tags -->
{% set all_tags = blog_topics( blog_id , 250) %}

<!-- create arrays -->
{% set topics = [] %}
{% set topics_final = [] %}

<!-- append topic data to the array -->
{% for item in module.add_topics.topics %}
  {% set topic_option = item|striptags %}
  {% do topics.append( topic_option ) %}
{% endfor %}

<!-- check if topic tags exists in HubSpot -->
{% for topics in all_tags %}
  {% if topics in all_tags %}
    {{ topics }}
    <!-- results with above 
    Data, Accounting, Insight
    -->  
  {% else %}
    else
  {% endif %}
{% endfor %}

With the above, it just prints out the {{ topics }}, even though Insight isn't in the all_tags array.

Note: Tagging Jinja2 as the syntax is similar

Upvotes: 1

Views: 579

Answers (1)

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39304

A combination of the filter reject and the built in test in could help you achieve this.

Sadly, it seems the reject filter does not accept negating a test, still, you can reject all the elements of topics that are not in all_tags then reject the said elements from the topics list.

So that ends with:

{{ topics | reject('in', topics | reject('in', all_tags) | list) | list }}

Switch yields:

[
    "Data",
    "Accounting"
]

Upvotes: 0

Related Questions