title: how do i place a sequential count or index based on a column value in mulesoft data weave?
body: <p>i need to write a sequence/index in a column based on values in another column. <strong>Please find sample below to explain my request :</strong>
  Here i need to generate index values in the customindex column based on the values in color column.. so basically if there are 4 rows with red in column, then it should index the rows as 1,2,3,4 and then when its 2 rows with blue as a value, it should again index from 1 -&gt; 1,2.</p>
  <p>Input data:</p>
  <pre><code>[
    {
      &quot;Type&quot;: &quot;Header&quot;,
      &quot;Color&quot;: &quot;Red&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    },
    {
      &quot;Type&quot;: &quot;Header&quot;,
      &quot;Color&quot;: &quot;Blue&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    },
    {
      &quot;Type&quot;: &quot;LineItem&quot;,
      &quot;Color&quot;: &quot;Red&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    },
    {
      &quot;Type&quot;: &quot;LineItem&quot;,
      &quot;Color&quot;: &quot;Red&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    },
    {
      &quot;Type&quot;: &quot;LineItem&quot;,
      &quot;Color&quot;: &quot;Blue&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    },
    {
      &quot;Type&quot;: &quot;Header&quot;,
      &quot;Color&quot;: &quot;Yellow&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    },
    {
      &quot;Type&quot;: &quot;LineItem&quot;,
      &quot;Color&quot;: &quot;Yellow&quot;,
      &quot;Customindex&quot;: &quot;&quot;
    }
  ]
  </code></pre>
  <p>here is the transformation that i need help with:</p>
  <pre><code>%dw 2.0
  output application/json
  var TM = flatten(payload map ((item, index) -&gt;
  [{
  &quot;Type&quot;:payload.type, //HEADER VALUES
  &quot;Color&quot;:&quot;&quot;,
  &quot;Customindex&quot;:&quot;&quot;
  }]++
  [{
  &quot;Type&quot;:payload.type,// LINE ITEM VALUES
  &quot;Color&quot;:payload.color,
  &quot;Customindex&quot;:index // need the index sequence to only count similar colors.. For ex : red start with 1,2,3 then for blue again 1,2 and so on
  }]))
  ---
  (((TM distinctBy $ ... filters and groupings
  </code></pre>
  <p><strong>Sample data with details (THIS IS THE EXPECTED OUTPUT):</strong>
  <a href="https://i.stack.imgur.com/UeXNv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UeXNv.png" alt="sample table custom index is the expected column" /></a></p>