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);
}
5
  • Your attempt looks like C#. Have you even tried to write anything in typescript before asking the question? Commented May 16, 2018 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. Commented May 16, 2018 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 Commented May 16, 2018 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. Commented May 16, 2018 at 13:05
  • stackoverflow.com/questions/22844560/… Commented May 16, 2018 at 13:37

1 Answer 1

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