Skip to content
Advertisement

How to filter by id?

const allStories = [{id: 5, title: 'Hello title'}, {id: 10, title: 'Hello title2'}];
const id = ["5","25","10"];
const book = allStories.filter(story => story.story_id === id);
console.log(book)

I want to filter stories by ids. I have tried to use .filter method but it is showing me empty array []

Advertisement

Answer

You have a few issues:

  1. You’re using .story_id when your object is using id
  2. You’re trying to check if a number is equal to the array id, this won’t work.

Instead, you can use .includes() method on your array to check if your (string) id from the object is included within the id array like so:

const allStories = [{id: 5, title: 'Hello title'}, {id: 10, title: 'Hello title2'}];
const id = ["5","25","10"];
const book = allStories.filter(story => id.includes(String(story.id)));
console.log(book)

If you want to remove the ids in the id array rather than keep them, you can negate the return value of .includes() using !.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement