yariv bar
yariv bar

Reputation: 976

add if/else logic to JavaScript filter

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?

Upvotes: 1

Views: 107

Answers (4)

Syed Afzal
Syed Afzal

Reputation: 150

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))
    );
  });

Upvotes: -2

Kumar
Kumar

Reputation: 3126

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)
            }
        );
    });

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371203

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.

Upvotes: 5

T.J. Crowder
T.J. Crowder

Reputation: 1075785

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.

Upvotes: 1

Related Questions