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

249 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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);

0
On

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);