1

I have an array of objects which I filter with two different arrays. The array is a list of study classes that I want to filter by grade and subject.

I came up with this code:

this.schoolActivity.filter(x => {
    return (
        this.activeSubjects.includes(x.subject.toLowerCase()) &&
        this.activeGrades.includes(x.grade)
    );
});

which works fine but the issue here is that if there are no active subjects (subject to filter by) or the same for a grade, then nothing returns. Any idea how can I improve this filter by adding logic to the only filter by subject/grade if active ones exist?

1
  • What does "no active subjects" mean? x.subject is blank, or this.activeSubjects is empty? Commented Aug 21, 2019 at 7:27

4 Answers 4

5

Just add an || check to see if the length of the array in question is 0:

const { activeSubjects, activeGrades } = this;
this.schoolActivity.filter(x => {
  return (
    (activeSubjects.length === 0 || activeSubjects.includes(x.subject.toLowerCase())) &&
    (activeGrades.length === 0 || activeGrades.includes(x.grade))
  );
});

You could improve the computational complexity to O(n) rather than O(n^2) by using a couple of Sets instead of includes, but that probably doesn't matter.

Sign up to request clarification or add additional context in comments.

1 Comment

I think you probably interpreted "no active subjects" better than I did.
1

If I understand you right, you want to skip the filter on x.subject if it's blank. In which case:

this.schoolActivity.filter(x => {
    return (
      (!x.subject || this.activeSubjects.includes(x.subject.toLowerCase())) &&
      this.activeGrades.includes(x.grade)
    );
  });

The first condition will be true if x.subject is blank or it isn't blank and is on the list of active subjects.

Comments

0

You can add logic to check if active Subjects & active grades exist

    this.schoolActivity.filter(x => {
        return (
            if(typeof this.activeSubjects !== 'undefined' && this.activeSubjects.length && typeof this.activeGrades !== 'undefined' && this.activeSubjects.length){
                this.activeSubjects.includes(x.subject.toLowerCase()) && this.activeGrades.includes(x.grade)
            }
        );
    });

Comments

-2

If I get your point then

this.schoolActivity.filter(x => {
    return (
      (this.activeSubjects && this.activeSubjects.includes(x.subject.toLowerCase())) &&
      (this.activeGrades && this.activeGrades.includes(x.grade))
    );
  });

Comments

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.