0

I'd like to filter this programs array (I've simplified the objects):

const programs = [
      {
        format: "In-Person",
        schedule: "Full-Time",
      },
      {
        format: "Remote",
        schedule: "Full-Time",
      },
      {
        format: "In-Person",
        schedule: "Part-Time",
      },
      {
        format: "Remote",
        schedule: "Part-Time",
      }
    ]

based on a filter object:

const filters = {format: "Remote", schedule:"Full-Time"}

My attempt:

  let filteredPrograms = programs.filter((program) => {
    return Object.entries(filters).every(([key, value]) => {
      program[key] == value;
    });
  });

This should analyze each program, and allow is to pass through the filter IF: For every filter key, the program[filter key] value matches the filter value

But I'm getting an empty array for filteredPrograms

ascentryan
  • 21
  • 3
  • but actually this is the problem: [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – pilchard Jan 28 '22 at 23:50

1 Answers1

0

Return the comparison result inside the every callback:

const programs=[{format:"In-Person",schedule:"Full-Time"},{format:"Remote",schedule:"Full-Time"},{format:"In-Person",schedule:"Part-Time"},{format:"Remote",schedule:"Part-Time"}],filters={format:"Remote",schedule:"Full-Time"};

let filteredPrograms = programs.filter((program) => {
  return Object.entries(filters).every(([key, value]) => {
    return program[key] == value;
  });
});
console.log(filteredPrograms)

Or make it an arrow function:

const programs=[{format:"In-Person",schedule:"Full-Time"},{format:"Remote",schedule:"Full-Time"},{format:"In-Person",schedule:"Part-Time"},{format:"Remote",schedule:"Part-Time"}],filters={format:"Remote",schedule:"Full-Time"};

let filteredPrograms = programs.filter((program) => {
  return Object.entries(filters).every(([key, value]) => program[key] == value);
});
console.log(filteredPrograms)
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    wow lol spent 3 hours on that and the docs for .every top example didn't show a return so I didn't even think of it. Thanks – ascentryan Jan 28 '22 at 23:34
  • This is a duplicate twice over, both the actual question and the syntax error. (also both of your snippets use arrow functions, but the second uses an implicit return) – pilchard Jan 28 '22 at 23:52