简体   繁体   中英

Remove Object have same property value from Array object when input is Array of property value Javascript

I have array objects:

[
    {
        id: 1,
        name: ABC,
        age: 10
    },
    {
        id: 2,
        name: ABCXYZ,
        age: 20
    },
    {
        id: 3,
        name: ZYXCNA,
        age: 30
    },
    ...
    ...
    ....more
]

and array is value of id in above array object: [ 1, 2]

then i want a array objects not have value of id in above array objects. Ex: Array objects i will receive in here is

[
    {
        id: 3,
        name: ZYXCNA,
        age: 30
    },
    {
        id: 4,
        name: ABCDX,
        age: 30
    }
] 

i have using 3 for loop in here to slove this problem but i think that can have smarter way. Like using reduce in here, but i still not resolved. Can anyone help me? Thanks so much.

You can do this using Array.filter & Array.includes .

 const source = [ { id: 1, name: 'ABC', age: 10 }, { id: 2, name: 'ABCXYZ', age: 20 }, { id: 3, name: 'ZYXCNA', age: 30 }, { id: 4, name: 'ABCDX', age: 30 } ]; const input = [ 1, 2 ]; const output = source.filter(({ id }) => !input.includes(id)); console.log(output);

Yo don't need any explicit loops at all, you're just filtering

 var input = [ { id: 1, name: "ABC", age: 10 }, { id: 2, name: "ABCXYZ", age: 20 }, { id: 3, name: "ZYXCNA", age: 30 }, ]; var ids = [1,2]; var result = input.filter(x => ! ids.includes(x.id)); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM