Javascript iterate an array with two conditions
Solution 1:
You could take a function for using with Array#some
and hand over the expected value.
const
has = string => o => o.name.includes(string),
levels = [{ name: 'first level primary school' }, { name: 'second level primary school' }, { name: 'first level secondary school' }],
isPrimarySchool = levels.some(has('primary')),
isSecondarySchool = levels.some(has('second'))
console.log(isPrimarySchool);
console.log(isSecondarySchool);
Solution 2:
I want to iterate the array and find if there is a string with the word 'primary' or 'secondary' and turn the value of isPrimarySchool or isSecondarySchool to true.
Using some()
with includes
const levels = [
{
name: 'first level primary school'
},
{
name: 'second level primary school'
},
{
name: 'first level secondary school'
}
]
const isPrimarySchool = levels.some(x=>x.name.toLowerCase().includes('primary'))
const isSecondarySchool = levels.some(x=>x.name.toLowerCase().includes('secondary'))
console.log({isPrimarySchool,isSecondarySchool})
Solution 3:
You could use the built-in Array.some()
function and some regexp:
isPrimarySchool = levels.some(level => /primary/.exec(level.name));
isSecondarySchool = levels.some(level => /secondary/.exec(level.name));