I have two arrays of dictionaries, both contain an ID property, one is 'id' and the other is '_id'.
I am trying to filter an array that contains all books available, and grab data from it based on what books a user has.
const books = allbooks.filter(({ id }) =>
userBooks.findIndex((book) => book._id === id)
)
This is the code I am using right now, but it's not doing what I expect.
What the data looks like
allbooks [
{
id: 1,
name: 'Book 1'
},
{
id: 2,
name: 'Book 2'
}
]
userBooks [
{
_id: 1
}
]
Should I create an array from the 2nd array's _ids and filter with that? Trying to find the best practice way of doing this, I am using arrays of dictionaries a lot and find it tough sometimes.
CodePudding user response:
You are sooo close my friend. The problem is Array.prototype.findIndex
is returning the first index in which your lambda function returns true. The index of the matching book is index 0, which is falsy, which makes your filter ignore it because the result of the filter lambda function is false.
Instead, you can check if the result of your findIndex is > -1 since Array.prototype.findIndex
returns -1 if the element is not found.
const allbooks = [
{
id: 1,
name: 'Book 1'
},
{
id: 2,
name: 'Book 2'
}
];
const userBooks = [
{
_id: 1
}
];
const books = allbooks.filter(({ id }) =>
userBooks.findIndex((book) => book._id === id) > -1
)
console.log(books);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>