title: Angular: How to use a groupBy Pipe in array
body: <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>import {
    Pipe,
    PipeTransform
  } from '@angular/core';
  
  /*
   * Group an array by a property (key)
   * Usage:
   *  value | groupBy : 'field'
   */
  
  @Pipe({
    name: 'groupBy'
  })
  export class GroupByPipe implements PipeTransform {
    transform(value: Array &lt; any &gt; , field: string): Array &lt; any &gt; {
      // prevents the application from breaking if the array of objects doesn't exist yet
      if (!value) {
        return null;
      }
      const groupedObj = value.reduce((previousVal, currentVal) =&gt; {
        if (!previousVal[currentVal[field]]) {
          previousVal[currentVal[field]] = [currentVal];
        } else {
          previousVal[currentVal[field]].push(currentVal);
        }
        return previousVal;
      }, {});
      // this will return an array of objects, each object containing a group of objects
      return Object.keys(groupedObj).map(key =&gt; ({
        key,
        value: groupedObj[key]
      }));
    }
  
  }</code></pre>
  </div>
  </div>
  </p>
  <p>I have implemented a custom groupBy pipe but it only works for a simple object string for instance it works when i pass something like this:</p>
  <pre><code>console.log(new GroupByPipe().transform(this.selectedServices, 'name'));
  </code></pre>
  <p>But i want to pass something more complex like this:</p>
  <pre><code>console.log(new GroupByPipe().transform(this.selectedServices,'paymentCycle.name'));
  </code></pre>
  <p>How can I make this pipe to accept a more complex groupBy such as this:</p>
  <pre><code>console.log(new GroupByPipe().transform(this.selectedServices, 'paymentCycle.name'));
  </code></pre>