Home > Mobile >  Angular Categorize and display title for list of items in *ngFor
Angular Categorize and display title for list of items in *ngFor

Time:10-27

I have an array of objects:

[{name: "Mary", "salary": "22k", "category": "A", "dob": 1992},
{name: "Bob", "salary": "22k", "category": "A", "dob": 1994},
{name: "Paul", "salary": "22k", "category": "A", "dob": 1994},
{name: "Christy", "salary": "22k", "category": "A", "dob": 1993},
{name: "John", "salary": "22k", "category": "A", "dob": 1993},
{name: "Kenny", "salary": "22k", "category": "A", "dob": 1993},
}]

I am displaying these from the template using *ngFor. But now I need to categorize based on dob (it will be grouped in order as shown) and display them under 1 title.

Ex:

Year 1992 Mary

Year 1994 Bob Paul

Year 1993 Christy John Kenny

I can achieve this by matching the index value or some other logic in a function. But let's just say we need to handle this only through *ngIf and *ngFor (or any other template changes). Is there a way?

CodePudding user response:

If you want to format the result before binding:

let arr = [{name: "Mary", "salary": "22k", "category": "A", "dob": 1992},
{name: "Bob", "salary": "22k", "category": "A", "dob": 1994},
{name: "Paul", "salary": "22k", "category": "A", "dob": 1994},
{name: "Christy", "salary": "22k", "category": "A", "dob": 1993},
{name: "John", "salary": "22k", "category": "A", "dob": 1993},
{name: "Kenny", "salary": "22k", "category": "A", "dob": 1993},
];

const years = [...new Set(arr.map(item => item.dob))];

const result = years.map(year => {
   return {
     year: year,
     names:  (arr.filter(p => p.dob === year  ).map(j => j.name)).join(' ')
   }
})
console.log(result);

CodePudding user response:

as Ali Adravi commented, you can use a Set to filter out duplicates from your source array.

In your component code:

const sourceArray = [...];
  ...
  const years = [...new Set(sourceArray.map(item => item.dob))];
  const categorizedItems = years.map(year => {
    return {
      year: year,
      names: sourceArray.filter(item => item.dob === year)
    }
  });
  ...

Then in your html file:

<div *ngFor="let item of items">
  <div >{{item.year}}</div>
    <div *ngFor="let person of item.names">
      <span >{{person.name}}</span>
    </div>        
</div>

Let me know if that helped!

  • Related