Home > front end >  How to filter items from array of objects based on another array of strings using javascript?
How to filter items from array of objects based on another array of strings using javascript?

Time:10-21

i want to filter the array of objects based on array of strings using javascript.

i have input array of object like so,

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']

now i want to filter the items in input whose id match with chosen_items. so the expected output is like below,

const output = [
    {
        id: 1,
        name: 'first',
        type: 'first_type',
    },
    {
        id: 2,
        name: 'second',
        type: 'second_type',
    },
]

i have tried like below but that gives wrong output. its maybe filtering the input based on index.

const output = React.useMemo(
  () => chosen_items.map(id => input[id]).filter(negate(isNil)),
  [input, chosen_items]
);

with above code snippet i get output like below,

output = [
    {
         id: 2,
         name: 'second',
         type: 'second_type',
     },
     {
         id: 3,
         name: 'third',
         type: 'third_type',
     },
 ]

could someone help me fix this. how to filter input based on its id. thanks.

CodePudding user response:

You can use filter() to do it,pay attention that in input,id is number,while in the chosen_items id is character.

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']

let result = input.filter(a => chosen_items.includes(a.id   ''))
console.log(result)

  • Related