0

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?

2 Answers 2

3
this.levels$.subscribe(levels =>{
this.isPrimarySchool =levels.some(level => level.name.toLowerCase().includes('primary'));
this.isSecondarySchool = levels.some(level => level.name.toLowerCase().includes('secondary'));
    })
Sign up to request clarification or add additional context in comments.

2 Comments

btw you can make a function for this => levels.some(level => level.name.toLowerCase().includes('secondary') therefore you wouldn't duplicate your code
Wouldn't it be better to use find here, since we only need one instance of primary/secondary occurring in order to determine the values?
0

You could use If/Else instead of 2 Ifs, and use a 3rd else.

Remember that using If/elsif/else will be less costly than adding 2 If's.

Or, you could ternary operators but that's most likely not a better approach.

2 Comments

In my opinion, if else is not a good solution here because for the example data both isPrimarySchool and isSecondarySchool can be true
That may be true, but my opinion is that using multiple IF statements makes it compulsory to check all conditions, while using if elsif if would only need one statement to be true, so first check would be for isPrimarySchool & isSecondarySchool, second for isPrimarySchool and last for isSecondarySchool.

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.