JavaScript
x
5
1
const allStories = [{id: 5, title: 'Hello title'}, {id: 10, title: 'Hello title2'}];
2
const id = ["5","25","10"];
3
const book = allStories.filter(story => story.story_id === id);
4
console.log(book)
5
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_id
when 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:
JavaScript
1
4
1
const allStories = [{id: 5, title: 'Hello title'}, {id: 10, title: 'Hello title2'}];
2
const id = ["5","25","10"];
3
const book = allStories.filter(story => id.includes(String(story.id)));
4
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 !
.