add if/else logic to JavaScript filter

yar*_*bar 1 javascript

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)
    );
});
Run Code Online (Sandbox Code Playgroud)

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?

Cer*_*nce 6

只需添加||检查以查看所讨论的数组的长度是否为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))
  );
});
Run Code Online (Sandbox Code Playgroud)

您可以将计算复杂度提高到,O(n)而不是O(n^2)通过使用几个Set而不是来提高includes,但这可能无关紧要。