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?

user1640256
  • 1,691
  • 7
  • 25
  • 48
  • 1
    Possible duplicate of [How to merge two arrays in Javascript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Seblor Aug 25 '17 at 12:55

1 Answers1

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392