'How do I filter an array getting loaded from the api using another static array in javascript or typescript?
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);
}
Solution 1:[1]
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))
Solution 2:[2]
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))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Divesh Pal |
| Solution 2 | alvaromartmart |
