Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter items from array of objects based on another array of strings using javascript?

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading