Zabih Khaliqi
Zabih Khaliqi

Reputation: 105

add to array if not already available Typescript

I have a two arrays:

Users [
  { "id": 0, "name": "Scott" },
  { "id": 0, "name": "Jan" },
  { "id": 0, "name": "Jack" },
]

Users2Add [
  { "id": 0, "name": "Scott" },
  { "id": 0, "name": "Andy" },
  { "id": 0, "name": "John" },
]

I want to check if new users in Users2Add are already in Users array. If yes don't push(add to array) else add the new User(From User2Add) to Users array. Like:

forEach(var u in Users2Add ) {
  if(!(Users.containts(x => x.id == User2Add.idx))) Users.push(u);
}

Upvotes: 0

Views: 479

Answers (1)

bugs
bugs

Reputation: 15313

The problem is that there's no straightforward way to check object equality in JS, and of course:

{a: 1} === {a: 1} //false

A possible solution is to use lodash:

Users2Add.forEach(user => {
  if (!Users.some(existingUser = > _.isEqual(existingUser, user))) {
    Users.push(user);
  }
});

Upvotes: 1

Related Questions