Answers.Body: <p>The accepted answer <a href="https://stackoverflow.com/questions/17788424/how-to-remove-duplicated-items-in-array-on-twig">here</a> should hopefully help you out.</p>
  
  <p>Basically:</p>
  
  <pre><code>{% set newArray = [] %}
  
  {% for name in array %}
     {% if name not in newArray %}
        My name is {{name}}
        {% set newArray = newArray|merge([name]) %}
     {% endif %}
  {% endfor %}
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-12-12T00:51:02.983Z
Answers.Text: Thanks Steve I've updated my question with your code sample.
Answers.UserDisplayName: R0wan
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-12-11T13:00:03.757Z
Answers.LastActivityDate: 2014-12-11T13:00:03.757Z
Answers.LastEditDate: 2017-05-23T12:38:53.957Z
Answers.UserDisplayName: Steve Abraham
Answers.Body: <h3>You could do it in the twig template</h3>
  <p>But a template isn't really the best place for something that is this codey, it gets pretty unreadable pretty quick.</p>
  <p>Notes:</p>
  <ul>
  <li>I start by building arrays of models and afterwards I convert those arrays to the comma-separated strings you require.</li>
  <li>It is case-sensitive, you probably have models or makes likes HILUX, hilux, Hilux, these sort of duplicates will not be removed. You can achieve a modicum of case-insensitivity by chucking a few <a href="http://twig.sensiolabs.org/doc/filters/lower.html" rel="nofollow noreferrer">lowers</a> in there.</li>
  <li>Instead of hand-writing the JSON, this uses <a href="http://twig.sensiolabs.org/doc/filters/json_encode.html" rel="nofollow noreferrer">twig's json_encode filter</a>; tweak the options to suit you.</li>
  </ul>
  <p>The template code:</p>
  <pre><code>{% set makes = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
  {% set data = {} %}
  
  {% for make in makes %}
      {% set make_name = make.make %}
  
      {# Get the list of models for this make if we have already seen it before, otherwise an empty array #}
      {% if data[make_name] is not defined %}
          {% set data = data|merge({(make_name):[]})%}
      {% endif %}
      {% set make_data = data[make_name] %}
  
      {# Build an array of model names #}
      {% set models = make.getChildren() %}
      {% for model in models %}
          {% set model_name = model.model %}
  
          {# Only add this model if we have not seen it before #}
          {% if model_name not in make_data %}
              {% set make_data = make_data|merge([model_name]) %}
          {% endif %}
      {% endfor %}
  
      {% set data = data|merge({(make_name):make_data}) %}
  {% endfor %}
  
  {# Replace the arrays of models we previously built with a comma-separated string of models #}
  {% for make_name, models in data %}
      {% set models_string = models|join(&quot;,&quot;) %}
      {% set data = data|merge({(make_name):models_string}) %}
  {% endfor %}
  
  {{ data|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}
  </code></pre>
  <h3>Or do it with code</h3>
  <p>Add your own plugin as per the instructions here: <a href="http://buildwithcraft.com/docs/plugins/setting-things-up" rel="nofollow noreferrer">Setting things up</a></p>
  <p>Add a template variable as per the instructions here: <a href="http://buildwithcraft.com/docs/plugins/variables" rel="nofollow noreferrer">Template variables</a></p>
  <p>Your template variable could look like this:</p>
  <pre><code>namespace Craft;
  
  class MyAwesomePluginVariable
  {
      public function getSearchData()
      {
          // find all makes
          $make_criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
          $make_criteria-&gt;level = 2;
          $make_criteria-&gt;section = array('usedCars','vansTrucks');
  
          $data = array();
  
          $makes = $make_criteria-&gt;find();
          foreach ($makes as $make) 
          {
              // build array of models for this make
              $model_names = array();
              $models = $make-&gt;getChildren();
              foreach ($models as $model) {
                  $model_names[]= $model-&gt;model;
              }
  
              // combine with previous models for this make and remove duplicates
              if (array_key_exists($make-&gt;make, $data)) {
                  $data[$make-&gt;make] = array_unique( array_merge($data[$make-&gt;make], $model_names) );
              } else {
                  $data[$make-&gt;make] = array_unique( $model_names );
              }
          }
  
          // convert model arrays to comma separated strings
          foreach ($data as $make =&gt; $models) {
              $data[$make] = implode(&quot;,&quot;, $models);
          }
  
          return $data;
      }
  
  }
  </code></pre>
  <p>And then in your template:</p>
  <pre><code>{{ craft.myAwesomePlugin.getSearchData|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}
  </code></pre>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2014-12-16T00:14:08.170Z
Answers.Text: Wow thanks! I made the Craft template variable as a plugin and it worked first time. Appreciate the help, learnt plenty from your examples.
Answers.UserDisplayName: R0wan
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2014-12-15T12:14:52.067Z
Answers.LastActivityDate: 2022-11-15T02:43:04.793Z
Answers.LastEditDate: 2022-11-15T02:43:04.793Z
Answers.UserDisplayName: Jeremy Allen
Body: <p><strong>Problem</strong></p>
  
  <p>I'm building a .json file for a search component of a used cars website. The file needs to be built from the output of two sections within CraftCMS, Used Cars and Vans &amp; Trucks. It outputs the "make" of vehicle and it's "models". </p>
  
  <p>My problem is that there are duplicate "makes"/"models" because they exist in both sections.</p>
  
  <p><strong>Code</strong>:</p>
  
  <pre><code>{% set allStock = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
  {% for stock in allStock %}
  {% set models = stock.getChildren() %}
  "{{ stock.make }}" : "{% for stock in models %}{{ stock.model }}{% if not loop.last %}, {% endif %}{% endfor %}"
  {% endfor %}
  </code></pre>
  
  <p><strong>Output</strong>:</p>
  
  <p>"Holden" : "Commodore, Ute, Viva"</p>
  
  <p>"Nissan" : "ATLAS, CARAVAN"</p>
  
  <p>"Mazda" : "ATENZA, Axela, CX-7, MAZDA 6, MPV, RX-8, mpv"</p>
  
  <p>"Nissan" : "CARAVAN, DUALIS, FAIRLADY, Liberty, Maxima, NAVARA, NOTE"</p>
  
  <p><strong>Updated</strong></p>
  
  <pre><code>{% set allStock = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
  {% set newArray = [] %}
  {% for stock in allStock %}
  {% set models = stock.getChildren() %}
  {% if stock.make not in newArray %}
  "{{ stock.make }}" : "{% for stock in models %}{{ stock.model }}{% if not loop.last %}, {% endif %}{% endfor %}"
  {% set newArray = newArray|merge([stock.make]) %}
  {% endif %}
  {% endfor %}
  </code></pre>
  
  <p>This code will remove the duplicate 'make' and merge but it also removes the models with it. </p>
  
  <p><strong>Output</strong>:</p>
  
  <p>"Holden" : "Commodore, Ute, Viva"</p>
  
  <p>"Mazda" : "ATENZA, Axela, CX-7, MAZDA 6, MPV, RX-8, mpv"</p>
  
  <p>"Nissan" : "CARAVAN, DUALIS, FAIRLADY, Liberty, Maxima, NAVARA, NOTE"</p>
  
  <p>Any help or direction on how to go about merging the models would be greatly appreciated.</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2014-12-12T07:01:30.427Z
Comments.Text: If you are comfortable with PHP, I would highly recommend building a simple plugin to handle this. That's a notable amount of logic for Twig to handle, you'd be better served putting it directly into PHP.
Comments.UserDisplayName: Lindsey D
Tags: <templating><array><merge>
Title: Using Twig to merge an array and remove duplicates
ThreadText: # Using Twig to merge an array and remove duplicates
  
  (Asked by: username_0 on 2014-12-11)
  
  **Problem**
  
  I'm building a .json file for a search component of a used cars website. The file needs to be built from the output of two sections within CraftCMS, Used Cars and Vans & Trucks. It outputs the "make" of vehicle and it's "models".
  
  My problem is that there are duplicate "makes"/"models" because they exist in both sections.
  
  **Code**:
  
  ```
  {% set allStock = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
  {% for stock in allStock %}
  {% set models = stock.getChildren() %}
  "{{ stock.make }}" : "{% for stock in models %}{{ stock.model }}{% if not loop.last %}, {% endif %}{% endfor %}"
  {% endfor %}
  
  ```
  
  **Output**:
  
  "Holden" : "Commodore, Ute, Viva"
  
  "Nissan" : "ATLAS, CARAVAN"
  
  "Mazda" : "ATENZA, Axela, CX-7, MAZDA 6, MPV, RX-8, mpv"
  
  "Nissan" : "CARAVAN, DUALIS, FAIRLADY, Liberty, Maxima, NAVARA, NOTE"
  
  **Updated**
  
  ```
  {% set allStock = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
  {% set newArray = [] %}
  {% for stock in allStock %}
  {% set models = stock.getChildren() %}
  {% if stock.make not in newArray %}
  "{{ stock.make }}" : "{% for stock in models %}{{ stock.model }}{% if not loop.last %}, {% endif %}{% endfor %}"
  {% set newArray = newArray|merge([stock.make]) %}
  {% endif %}
  {% endfor %}
  
  ```
  
  This code will remove the duplicate 'make' and merge but it also removes the models with it.
  
  **Output**:
  
  "Holden" : "Commodore, Ute, Viva"
  
  "Mazda" : "ATENZA, Axela, CX-7, MAZDA 6, MPV, RX-8, mpv"
  
  "Nissan" : "CARAVAN, DUALIS, FAIRLADY, Liberty, Maxima, NAVARA, NOTE"
  
  Any help or direction on how to go about merging the models would be greatly appreciated.
  
  **Tags:** templating, array, merge
  
  > **Comments:**
  > **username_1**: If you are comfortable with PHP, I would highly recommend building a simple plugin to handle this. That's a notable amount of logic for Twig to handle, you'd be better served putting it directly into PHP.  
  
  ---
  
  ## 2 answers
  
  ### Answer by username_3 on 2014-12-15. Score: 9 | Accepted answer
  
  ### You could do it in the twig template
  
  But a template isn't really the best place for something that is this codey, it gets pretty unreadable pretty quick.
  
  Notes:
  
  * I start by building arrays of models and afterwards I convert those arrays to the comma-separated strings you require.
  * It is case-sensitive, you probably have models or makes likes HILUX, hilux, Hilux, these sort of duplicates will not be removed. You can achieve a modicum of case-insensitivity by chucking a few [lowers](http://twig.sensiolabs.org/doc/filters/lower.html) in there.
  * Instead of hand-writing the JSON, this uses [twig's json\_encode filter](http://twig.sensiolabs.org/doc/filters/json_encode.html); tweak the options to suit you.
  
  The template code:
  
  ```
  {% set makes = craft.entries.section(['usedCars','vansTrucks']).level(2) %}
  {% set data = {} %}
  
  {% for make in makes %}
      {% set make_name = make.make %}
  
      {# Get the list of models for this make if we have already seen it before, otherwise an empty array #}
      {% if data[make_name] is not defined %}
          {% set data = data|merge({(make_name):[]})%}
      {% endif %}
      {% set make_data = data[make_name] %}
  
      {# Build an array of model names #}
      {% set models = make.getChildren() %}
      {% for model in models %}
          {% set model_name = model.model %}
  
          {# Only add this model if we have not seen it before #}
          {% if model_name not in make_data %}
              {% set make_data = make_data|merge([model_name]) %}
          {% endif %}
      {% endfor %}
  
      {% set data = data|merge({(make_name):make_data}) %}
  {% endfor %}
  
  {# Replace the arrays of models we previously built with a comma-separated string of models #}
  {% for make_name, models in data %}
      {% set models_string = models|join(",") %}
      {% set data = data|merge({(make_name):models_string}) %}
  {% endfor %}
  
  {{ data|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}
  
  ```
  
  ### Or do it with code
  
  Add your own plugin as per the instructions here: [Setting things up](http://buildwithcraft.com/docs/plugins/setting-things-up)
  
  Add a template variable as per the instructions here: [Template variables](http://buildwithcraft.com/docs/plugins/variables)
  
  Your template variable could look like this:
  
  ```
  namespace Craft;
  
  class MyAwesomePluginVariable
  {
      public function getSearchData()
      {
          // find all makes
          $make_criteria = craft()->elements->getCriteria(ElementType::Entry);
          $make_criteria->level = 2;
          $make_criteria->section = array('usedCars','vansTrucks');
  
          $data = array();
  
          $makes = $make_criteria->find();
          foreach ($makes as $make) 
          {
              // build array of models for this make
              $model_names = array();
              $models = $make->getChildren();
              foreach ($models as $model) {
                  $model_names[]= $model->model;
              }
  
              // combine with previous models for this make and remove duplicates
              if (array_key_exists($make->make, $data)) {
                  $data[$make->make] = array_unique( array_merge($data[$make->make], $model_names) );
              } else {
                  $data[$make->make] = array_unique( $model_names );
              }
          }
  
          // convert model arrays to comma separated strings
          foreach ($data as $make => $models) {
              $data[$make] = implode(",", $models);
          }
  
          return $data;
      }
  
  }
  
  ```
  
  And then in your template:
  
  ```
  {{ craft.myAwesomePlugin.getSearchData|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}
  
  ```
  
  > **Comments:**
  > **username_0**: Wow thanks! I made the Craft template variable as a plugin and it worked first time. Appreciate the help, learnt plenty from your examples.  
  
  ---
  
  ### Answer by username_2 on 2014-12-11. Score: 6
  
  The accepted answer [here](https://stackoverflow.com/questions/17788424/how-to-remove-duplicated-items-in-array-on-twig) should hopefully help you out.
  
  Basically:
  
  ```
  {% set newArray = [] %}
  
  {% for name in array %}
     {% if name not in newArray %}
        My name is {{name}}
        {% set newArray = newArray|merge([name]) %}
     {% endif %}
  {% endfor %}
  
  ```
  
  > **Comments:**
  > **username_0**: Thanks username_2 I've updated my question with your code sample.  
  
  ---
  
  