3

I have two arrays of objects:

var existingUsers1 = [];
    existingUsers1.push({
        "userName": "A",
        "departmentId": "1"
    });
    existingUsers1.push({
        "userName": "B",
        "departmentId": "1"
    });
    existingUsers1.push({
        "userName": "C",
        "departmentId": "1"
    });
    existingUsers1.push({
        "userName": "D",
        "departmentId": "1"
    });

var existingUsers2 = [];
    existingUsers2.push({
        "userName": "A",
        "departmentId": "1"
    });
    existingUsers2.push({
        "userName": "B",
        "departmentId": "1"
    });

I need to find the objects from existingUsers1 that are not present in existingUsers2. Is there any function in nodeJS that I can use to achieve this or any other way?

1

1 Answer 1

3

You could use a Set with Array#filter.

var existingUsers1 = [{ userName: "A", departmentId: "1" }, { userName: "B", departmentId: "1" }, { userName: "C", departmentId: "1" }, { userName: "D", departmentId: "1" }],
    existingUsers2 = [{ userName: "A", departmentId: "1" }, { userName: "B", departmentId: "1" }],
    hash = new Set(existingUsers2.map(o => o.userName)),
    result = existingUsers1.filter(o => !hash.has(o.userName));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

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.