title: How to group items in dynamic array using Javascript
body: <p>Here is simple Javascript problem. I have two arrays fruits and basket. Basket is always sorted. </p>
  
  <pre><code>var fruits = [''];
  var basket = ["Apple", "Apple", "Banana", "Orange", "Orange", "Orange"];
  </code></pre>
  
  <p>I want each element of basket to be grouped like this.</p>
  
  <pre><code>Apple
  I have Apple
  I have Apple
  
  Banana
  I have Banana
  
  Orange
  I have Orange
  I have Orange
  I have Orange
  </code></pre>
  
  <p>Code
      HTML</p>
  
  <pre><code>&lt;div id="table"&gt;&lt;/div&gt;
  </code></pre>
  
  <p>Code JS</p>
  
  <pre><code>var fruits = [''];
  var basket = ["Apple", "Apple", "Banana", "Orange", "Orange", "Orange"];
  
  for (var i = 0; i &lt; basket.length; i++) { 
    var fruit = basket[i];
  
    for (var j = 0; j &lt; fruits.length; j++) {
      if (fruit == fruits[j]) {
        // Existing fruit
        $("#table").append("I have " + fruit);
        break;
      } else {
        // New fruit
        $("#table").append("&lt;h1&gt;" + fruit + "&lt;/h1&gt;");
        $("#table").append("I have " + fruit);
        fruits.push(fruit);
        break;
      }
  }
  </code></pre>
  
  <p>This code doesn't work. It ends up looking like this. How do I fix? Fruits inside basket could be different so this should be dynamic. </p>
  
  <pre><code>Apple
  I have Apple
  
  Apple
  I have Apple
  
  Banana
  I have Banana
  
  Orange
  I have Orange
  
  Orange
  I have Orange
  
  Orange
  I have Orange
  </code></pre>