In my JavaScript code, I am looking to filter an array of objects based on an array of strings.
Here is the input array of objects:
const input = [
{
id: 1,
name: 'first',
type: 'first_type',
},
{
id: 2,
name: 'second',
type: 'second_type',
},
{
id: 3,
name: 'third',
type: 'third_type',
},
];
const chosen_items = ['1','2']
The goal is to filter the items in the input array whose id matches with the ids in the chosen_items array. The expected output should be as follows:
const output = [
{
id: 1,
name: 'first',
type: 'first_type',
},
{
id: 2,
name: 'second',
type: 'second_type',
},
]
I attempted a solution using React's useMemo hook, but it did not give the correct output. It seems to be filtering based on index rather than id.
const output = React.useMemo(
() => chosen_items.map(id => input[id]).filter(negate(isNil)),
[input, chosen_items]
);
As a result, the output I got was different from what I expected:
output = [
{
id: 2,
name: 'second',
type: 'second_type',
},
{
id: 3,
name: 'third',
type: 'third_type',
},
]
If anyone can help me fix this issue and correctly filter the input array by id, I would greatly appreciate it. Thank you!