0

I'm trying to do a multiple filter in javascript. It consists in 5 filters: search input, maxYear, minYear and if a string contains one item of an array of strings (x2).

I started doing this:

let entries = formattedJsonResults;

if (search) {
  const filtered = entries.filter(entry =>
    entry.title.toLowerCase().includes(search.toLowerCase())
  );
  entries = filtered;
} else if (minYear) {
  const filtered = entries.filter(entry =>
    Number(entry.date.slice(0, 4)) >= minYear.getFullYear()
  );
  entries = filtered;
} else if (maxYear) {
  const filtered = entries.filter(entry =>
    Number(entry.date.slice(0, 4)) <= maxYear.getFullYear()
  );
  entries = filtered;
}

But later I realized that they are not compatible. Eg, if search exists, I'll never access to the minYear filter.

Can someone help me please? thanks

1
  • What is search, etc? Commented Apr 13, 2022 at 17:55

1 Answer 1

1

Use individual if-statements, rather than an if-else. Also, use the previously filtered result for the next filter.

const entries = formattedJsonResults;
let filtered = entries;

// Filter by search term
if (search) {
  filtered = filtered.filter(entry =>
    entry.title.toLowerCase().includes(search.toLowerCase())
  );
}

// Filter by minimum year
if (minYear) {
  filtered = filtered.filter(entry =>
    Number(entry.date.slice(0, 4)) >= minYear.getFullYear()
  );
}

// Filter by maximum year
if (maxYear) {
  filtered = filtered.filter(entry =>
    Number(entry.date.slice(0, 4)) <= maxYear.getFullYear()
  );
}

// Filter by annotations
if (annotations) {
  filtered = filtered.filter(entry =>
    annotations.includes(entry.annotation)
  );
}

console.log(filtered); // After filtering 1x to 4x
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! and now I added another filter that consists in the following: I have one parameter called annotations, which is a string of words separated with commas (eg: video, image, GPS), and also a filter where I select one or many of them. How could I filter my array to know if the selected entry has at least one of the selected filters? thanks
@Emiliano either 'video, image, GPS'.split(/,\s*/g).includes(str) or 'video, image, GPS'.includes(str). I updated the response above to include the latter usage.

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.