0

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);
}
Zabih Khaliqi
  • 85
  • 1
  • 8
  • Your attempt looks like C#. Have you even tried to write anything in typescript before asking the question? – Yury Tarabanko May 16 '18 at 12:22
  • @YuryTarabanko what I have written is not an attempt rather a piece of code to give you a better picture of the problem. – Zabih Khaliqi May 16 '18 at 12:31
  • So you basically haven't tried anything. This is not how SO works. You have to make some research on your own, try to implement it (this is basic stuff) and ask for a specific question if you run into a problem. [How to Ask](https://stackoverflow.com/help/how-to-ask) – Yury Tarabanko May 16 '18 at 12:38
  • I have tried. and done some research too. I tried array.map and array.indexOf. indexOf doesn't work in this context since I have an array of objects. and Using array.map I was unable to write a function to get the required target. – Zabih Khaliqi May 16 '18 at 13:05
  • https://stackoverflow.com/questions/22844560/check-if-object-value-exists-within-a-javascript-array-of-objects-and-if-not-add/22844712 – Yury Tarabanko May 16 '18 at 13:37

1 Answers1

1

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);
  }
});
bugs
  • 14,631
  • 5
  • 48
  • 52