title: Use javascript to convert form with arrays to comma separated query strings without duplicates
body: <p>I want to change a query string from </p>
  
  <p><strong>?firstArray[]=0001&amp;firstArray[]=0002&amp;secondArray[]=0003&amp;secondArray[]=0004</strong> to 
  <strong>?firstArray=0001,0002&amp;secondArray=0003,0004</strong></p>
  
  <p>I think I'm almost there, but the problem I have is that the array values are the same for both arrays after my javascript is done processing the form. Here's the form:</p>
  
  <pre><code>&lt;form method="get" action="" class="productFilter"&gt;
      &lt;input type="checkbox" name="firstArray[]" id="" value="0001"&gt;0001
      &lt;input type="checkbox" name="firstArray[]" id="" value="0002"&gt;0002
      &lt;input type="checkbox" name="secondArray[]" id="" value="0003"&gt;0003
      &lt;input type="checkbox" name="secondArray[]" id="" value="0004"&gt;0004
      &lt;input type="submit" name="submit" value="test"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>And here's the javacript/jquery:</p>
  
  <pre><code>$('.productFilter').on('submit', function() {
  
  var newVal = [];
  var seen = {};
  
  // Gather values into array.
  $('input[name$="[]"]:checked').each(function() {
      newVal.push($(this).val());
  });
  
  // Make comma-separated list of values.
  var commaSeparated = newVal.join(',');
  console.log(commaSeparated);
  
  // Remove duplicates so an 'array' is only listed once in the query string.
  $('input[name$="[]"]:checked').each(function() {
      var name = $(this).attr('name');
      if (seen[name]) {
          $(this).remove();
      }
      else {
          seen[name] = true;
      }
      $(this).attr('name', name.slice(0, -2)).val(commaSeparated);
  });
  </code></pre>
  
  <p>});</p>
  
  <p>I understand why my 'commaSeparated' var contains the values of both the firstArray and secondArray inputs, so when I check all the boxes, the resulting query string is:</p>
  
  <p>?firstArray=0001,0002,0003,0004&amp;secondArray=0001,0002,0003,0004 
  when I want it to be 
  ?firstArray=0001,0002&amp;secondArray=0003,0004</p>
  
  <p>I'm not sure how to fix it though. I would need to store the values of the form arrays in separate variables, right? It should be noted that I don't know how many form elements there will be and what they will be called in my production code.</p>