1

I have this array and would like to categorize the name value, based on the group value in my HTML file.

This is a snippet of relevant parts from my .TS file where I have the arrays.

export let Students = [
    {
     'name': 'Alex',
     'age': '14',
     'group': 'Regular',
    },

I have tried to remove the tags, but that does not give the desired result. I feel like that there is a much more efficient and simple way of going about this.

1 Answer 1

2

You could group your first array by group, and then iterate over both array. :

 //so we can access "this" in the callback. 
 let parent = this;
 this.Students.forEach((item) => {
    if(!parent.groupedStudents.hasOwnProperty(item.group)) {
        parent.groupedStudents[item.group] = { title: item.group, students: []}
    }
    parent.groupedStudents[item.group].students.push(item);
});
// we cannot iterate over object in ngFor, so we use only the values.
this.groupedStudents = Object.values(this.groupedStudents);

And in your template

<ng-container *ngFor="let item of main.groupedStudents">
    <ion-list-header>
        <ion-label>{{item.title}}</ion-label>
    </ion-list-header>

    <ion-label *ngFor="let student of item.students>{{student.name}}</ion-label>
</ng-container>

I have made a basic angular app using this here

Sign up to request clarification or add additional context in comments.

4 Comments

at what line and what's the code associated with that line in your TS file ?
Check the way you are accessing the Students variable. maybe you don't need the this. @ellierad
You probably have to remove the this aswell. I'm using my code in a Angular type of way, that's why i'm using this.
Also, groupedStudents is suposed to be a class variable in my angular.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.