Home > database >  How do I filter an array getting loaded from the api using another static array in javascript or typ
How do I filter an array getting loaded from the api using another static array in javascript or typ

Time:03-04

I am trying to load the sectionRoles which only contains the one given in the array in filterData function but it doesn't return the filtered items.

How do I do this?

Simply, see the data contains a lot records but I want it to contain only the record which are given in the array.

  async getAllSectionRoles() {
        debugger;
        let data = await this.adminService.getAllSectionRoles().toPromise();
        this.sectionRoles = data;
        this.sectionRoles = data.filter(item => this.filterData(item.Id))
      }
    
      filterData(itemId) {
        let arr= [SectionRoleType.ResearchAndStudy,
                  SectionRoleType.Readings,
                  SectionRoleType.TaqareerAlBahasElmi,
                  SectionRoleType.TaqreerMoqaf,
                  SectionRoleType.WarqaSeyassie,
                  SectionRoleType.Derasat,
                  SectionRoleType.TaqareerDawreya,
                  SectionRoleType.ErhaabDowaly
                ];
    
        return arr.find(itemId);
  }

CodePudding user response:

I think instead of array , you can use Set here

Assuming your item.id is one of values from SectionRoleType

let arr= [SectionRoleType.ResearchAndStudy,
                  SectionRoleType.Readings,
                  SectionRoleType.TaqareerAlBahasElmi,
                  SectionRoleType.TaqreerMoqaf,
                  SectionRoleType.WarqaSeyassie,
                  SectionRoleType.Derasat,
                  SectionRoleType.TaqareerDawreya,
                  SectionRoleType.ErhaabDowaly
                ];
const filters = new Set(arr);

and then

this.sectionRoles = data.filter(item => filters.has(item.Id))

CodePudding user response:

You can use Array.includes for that

const arr= [SectionRoleType.ResearchAndStudy,
                  SectionRoleType.Readings,
                  SectionRoleType.TaqareerAlBahasElmi,
                  SectionRoleType.TaqreerMoqaf,
                  SectionRoleType.WarqaSeyassie,
                  SectionRoleType.Derasat,
                  SectionRoleType.TaqareerDawreya,
                  SectionRoleType.ErhaabDowaly
                ];
this.sectionRoles = data.filter(item => arr.includes(item.Id))
  • Related