I need help filtering an array based on values from another array. The first array consists of objects with dropdown options, while the second array contains values that should match with the first array. How can I achieve this?
1st Array:
const books = [
{
label: "To Kill a Mockingbird",
value: 1
},
{
label: "1984",
value: 2
},
{
label: "The Lord of the Rings",
value: 3
},
{
label: "The Great Gatsby",
value: 4
}
]
Code Snippet provided:
const idString = "1,2,3";
function getSelectedOption(idString, books) {
const ids = idString.split(",");
const selectedOptions = [];
ids.map(e => {
const selected = books.map(options => {
if (options.value === e){
return {
label: options.label,
value: options.value
}
}
})
selectedOptions.push(selected)
})
return selectedOptions
}
Result obtained:
[
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, undefined]
]
Expected Outcome:
[
{
label: "To Kill a Mockingbird",
value: 1
},
{
label: "1984",
value: 2
},
{
label: "The Lord of the Rings",
value: 3
}
]