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:
- You’re using
.story_idwhen your object is usingid - 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 !.