0

Does anyone know how to filter out reporting results in am angular 2 dropdown list. I am currently trying to do it within the template *ngFor but having no luck. I will try a custom pipe too. The data is from a JSON array. In the below object I am trying to only show one instance of "State Owned Entities"

Result in dropdown

My data object

items[
      {  
       "currentBUName":"Financial Services"
      }
      {  
       "currentBUName":"State Owned Entities"
      }
      {  
       "currentBUName":"State Owned Entities"
      }
     ]

My ts code extract

    <ion-item>
     <ion-label>Please select current business unit</ion-label>
      <ion-select [(ngModel)]="selectedValue">
          <ion-option *ngFor="let indexx of this.items;"[value]="indexx">{{indexx.currentBUName}}</ion-option>
      </ion-select>
    </ion-item>
skydev
  • 1,867
  • 9
  • 37
  • 71
  • Thanks for the responses but I eventually used this function thanks to Yoav Schniederman from this link http://stackoverflow.com/questions/41867448/in-angular2-ngfor-iteration-how-do-i-output-only-unique-values-from-the-array `transform(){ if(this.items!== undefined && this.items!== null){ console.log(_.uniqBy(this.items, 'currentBUName')); this.currentBUvals = _.uniqBy(this.items, 'currentBUName'); return _.uniqBy(this.items, 'currentBUName'); } return this.items; }` – skydev Apr 26 '17 at 06:11

3 Answers3

0

When you set the value of items use a filter function to only get the unique values. This can be done like so:

this.items = this.items.filter((v, i, arr) => arr.indexOf(v) === i);

NOTE: If this data is coming from a server then it would make more sense to do this filtering server-side to reduce the amount of duplicate information that is coming across the wire.

Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
0

Why not use an array filter ?

items = [
  {  
   "currentBUName":"Financial Services"
  }
  {  
   "currentBUName":"State Owned Entities"
  }
  {  
   "currentBUName":"State Owned Entities"
  }
 ]
uniqueItems = items.filter(function(item, pos) {
    return items.indexOf(item) == pos;
})

then use uniqueItems instead

Ismail H
  • 4,226
  • 2
  • 38
  • 61
0

Other answers are good but one way you might do this would be to define it in terms of some more general utility functions

function groupBy<T>(values: T[], keySelector: (value: T) => string): {[key: string]: T[]} {
  return values
      .map(value => ({ key: keySelector(value), value }))
      .reduce((groups, { key, value }) => ({
        ...groups,
        [key]: groups[key] && groups[key].concat(value) || [value]
      }), {});
}

function distinctBy<T>(values: T[], keySelector: (value: T) => string): T[] {
  const groups = groupBy(values, keySelector);
  return Object.values(groups).map(([representative]) => representative);
}

Then you could write

this.items = distinctBy(incomingItems, item => item.currentBUName);
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84