Kavya
Kavya

Reputation: 53

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

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?

Upvotes: 0

Views: 814

Answers (3)

Ali Adravi
Ali Adravi

Reputation: 22763

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);

Once you have formatted data, easily you can bind them, it will create the final list:

[
  { "year": 1992, "names": "Mary" },
  { "year": 1994, "names": "Bob Paul" },
  { "year": 1993, "names": "Christy John Kenny" }
]

Upvotes: 1

Kavya
Kavya

Reputation: 53

I just found this solution from another post. Had to only update the HTML: https://stackoverflow.com/a/58923774/4567978

Upvotes: 0

saguirrews
saguirrews

Reputation: 330

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 class="year">{{item.year}}</div>
    <div *ngFor="let person of item.names">
      <span class="personName">{{person.name}}</span>
    </div>        
</div>

Let me know if that helped!

Upvotes: 1

Related Questions