Angular iterate an array with two conditions
I have this array and these values:
levels$: Observable<any[]> = [
{
name: 'first level primary school'
},
{
name: 'second level primary school'
},
{
name: 'first level secondary school'
}
]
const isPrimarySchool = false
const isSecondarySchool = false
And I want to iterate the array and find if there is a string with the word 'primary' or 'secondary' (it could be both), and turn the value of isPrimarySchool or isSecondarySchool to true, or both if it's the case.
The method that I found to resolve this, is this one:
this.levels$.subscribe(levels =>
levels.forEach(level => {
if (level.name.toLowerCase().includes('primary') {
this.isPrimarySchool = true
}
if (level.name.toLowerCase().includes('secondary')) {
this.isSecondarySchool = true
}
})
)
Is there a better way to resolve the two 'if' parts, using lodash or normal javascript?
Solution 1:
this.levels$.subscribe(levels =>{
this.isPrimarySchool =levels.some(level => level.name.toLowerCase().includes('primary'));
this.isSecondarySchool = levels.some(level => level.name.toLowerCase().includes('secondary'));
})