0

I have the following class in an Angular app:

export class BenefitSettingModel {
    benefitSettingId: string;
    benefitSettingName: string;
    benefitGroupId: number;
    benefitGroupName: string;
}

Looping through an array in my view, I am displaying all benefitGroupName values with {{benefitSettingList[i].benefitGroupName}}

A lot of these values are identical and I only want to display unique ones. How can I display only the disinct values for benefitGroupName?

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
noclist
  • 1,659
  • 2
  • 25
  • 66
  • 2
    You basically want to collect those values into an array, and then filter it down to only unique values. [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – Alex Wayne Apr 02 '20 at 20:18

2 Answers2

2

You should be able to create a helper function somewhere to get this list of group names for you. You can use a Set to make an array have only distinct values.

function groupNames(benefitSettings: BenefitSettingModel[]): string[] {
  // Get array of all group names.
  const groups = benefitSettings.map(model => model.benefitGroupName)

  // Use a Set to reduce to only unique entries.
  return [...new Set(groups)]
}
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
0

I don't know exactly how you iterate over your elements, but I assume you could use an array filter with a simple dictionary to prevent duplicates:

        let cache = {}
        let listWithoutDups = listOfBenefitGroupSettigns.filter((e) => {
            if(cache[e.benefitGroupName]){
                return false
            } else {
                cache[e.benefitGroupName] = true
                return true
            }
        })

or during iteration, something like this;

  let cache = {}
  listOfBenefitGroupSettigns.forEach((benefitSettingList) => {
    if(!cache[benefitSettingList.benefitGroupName]){
      cache[benefitSettingList.benefitGroupName] = true
      {{benefitSettingList.benefitGroupName}}
    }
  })
Automatico
  • 12,420
  • 9
  • 82
  • 110