title: Javascript merge objects in array by values
body: <p>In Javascript, I have an array with objects that looks like this:</p>
  
  <pre><code>var arr = [
      {
          value_1: 0,
          value_2: 4,
          encounter_bits: {
              min_level: 8,
              max_level: 12,
              rarity: 20,
              conditions: [1, 5]
          }
      },
      {
          value_1: 1,
          value_2: 4,
          encounter_bits: {
              min_level: 5,
              max_level: 5,
              rarity: 20,
              conditions: [2, 9]
          }
      },
      {
          value_1: 0,
          value_2: 4,
          encounter_bits: {
              min_level: 8,
              max_level: 12,
              rarity: 5,
              conditions: [1, 5]
          }
      },
  ];
  </code></pre>
  
  <p>I need to merge the objects that have the same min_level, max_level and conditions. The merged objects will have their rarity added up. I also need to preserve the array order.</p>
  
  <p>So arr[0] and arr[2] will become:</p>
  
  <pre><code>    arr[0] = {
          value_1: 0,
          value_2: 4,
          encounter_bits: {
              min_level: 8,
              max_level: 12,
              rarity: 25,
              conditions: [1, 5]
          }
      }
  </code></pre>
  
  <p>From roughly the same dataset, this is being done in Python:</p>
  
  <pre><code># Combine "level 3-4, 50%" and "level 3-4, 20%" into "level 3-4, 70%".
  existing_encounter = filter(lambda enc: enc['min_level'] == encounter.min_level
                                      and enc['max_level'] == encounter.max_level,
                              encounter_bits)
  if existing_encounter:
      existing_encounter[0]['rarity'] += encounter.slot.rarity
  else:
      encounter_bits.append({
          'min_level': encounter.min_level,
          'max_level': encounter.max_level,
          'rarity': encounter.slot.rarity,
      })
  </code></pre>
  
  <p>I know I might have to do something with array.sort and array.splice but I can't figure this out. What would be the most efficient way to achieve this?</p>