0

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.

1

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.