-1

I have an empty array

const someArray = []

and then I have another array of 2 objects (can vary)

let users = [
    {
        id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
        name: 'John Doe',
        age: 50,
    },
    {
        id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
        name: 'Jane Doe',
        age: 45,
    },
];

the id key which make users unique.

As you can see I have 2 users with same id I only want to add the first one. What I did so far

users.forEach((user) => {
  if (!someArray.includes(user.id)) {
    someArray.push(user);
  }
});

// OTHER METHOD I USED
users.forEach((user) => {
  if (someArray.some((element) => element.id !== user.id)) {
    someArray.push(user);
  }
});

The first method appending both elements even thier id's are same and the second method is doing nothing or is not appending anything.

Kunal Tanwar
  • 1,209
  • 1
  • 8
  • 23
  • 2
    In the first code, `someArray.push(user.id)` to get the `includes` to match on id - at the moment, it's comparing `id` with `user` which will never match. Would give you a list of unique IDs, so you push the user object to a 2nd array; this is if you want to use `.includes(user.id)` – freedomn-m Mar 01 '22 at 07:12
  • 1
    In the second code, as `.some` = "any" or "at least one" as it starts empty, it never has "any" that don't match. Equally, once it gets a single value, all the other values will be added as they'll always be at least one that doesn't match (unless they're all the same as in your example) – freedomn-m Mar 01 '22 at 07:15
  • I suggest you fix the source of your data - if the guid is meant to be unique, then there should never be two values for you to worry about in your front end. If this is in a DB and you're trying to find the duplicates then use a SQL query such as `SELECT id, count(id) FROM users GROUP BY id HAVING count(id)>1 ORDER BY 2 DESC` to find offending duplicate IDs. Your code as-is will just dump/delete the duplicates, which can't be good for those users. – freedomn-m Mar 01 '22 at 07:17
  • @freedomn-m Thanks for the explanation but I am not using any `BACKEND` or `DB` right now. It is just a frontend project I am doing right now. Also In real code I am trying to save things in `localstorage`. – Kunal Tanwar Mar 01 '22 at 07:20
  • You can also "group by" in js, see [this answer](https://stackoverflow.com/a/40774906/2181514) and [this fiddle](https://jsfiddle.net/qwytzL0x/) with it applied. – freedomn-m Mar 01 '22 at 07:20
  • @KunalTanwar, Could you check this example https://codepen.io/Maniraj_Murugan/pen/bGYQdpp – Maniraj Murugan Mar 01 '22 at 07:25
  • [This answer](https://stackoverflow.com/a/56768137/2181514) gives your code as: `const unique = [...new Map(users.map(item => [item["id"], item])).values()]` **Edit** except that gives the last one, not the first one - but there's numerous other solutions on that question. Such as `unique = users.filter((value, index, self) => index === self.findIndex((t) => ( t.id === value.id )));` – freedomn-m Mar 01 '22 at 07:26
  • 1
    Does this answer your question? [How to remove all duplicates from an array of objects?](https://stackoverflow.com/questions/2218999/how-to-remove-all-duplicates-from-an-array-of-objects) – freedomn-m Mar 01 '22 at 07:26
  • @ManirajMurugan Can you explain how did you do in that code and also I am getting new array not the one I want. I don't want a new array I want `someArray` to work. – Kunal Tanwar Mar 01 '22 at 07:34
  • 1
    @KunalTanwar in the code pen, change `const data = users.reduce` to `const someArray = users.reduce` or push all the results of `data` into your existing `someArray` if you must have it created up-front. – freedomn-m Mar 01 '22 at 07:35
  • 1
    @KunalTanwar, Then just change ```const data = users.reduce``` to ```const someArray = users.reduce``` . Updated codepen https://codepen.io/Maniraj_Murugan/pen/bGYQdpp – Maniraj Murugan Mar 01 '22 at 07:37
  • 1
    Why is the word “empty” in the question title (if the array is empty you don’t need to check anything at all - it is empty and definitely does not contain the object)? Please edit the question to be clearer. – AD7six Mar 01 '22 at 07:39
  • @AD7six Because the initally array is empty. I have tried to find on SO on Google but couldn't find question similar to mine. – Kunal Tanwar Mar 01 '22 at 07:40
  • That sounds like a stretch :), what difference does it make if it’s initialised empty or not?. **Please edit the question to be clearer** – AD7six Mar 01 '22 at 07:48
  • 1
    please check existing thread on stackoverflow > https://stackoverflow.com/questions/4587061/how-to-determine-if-object-is-in-array – Muhammad Muzamil Mar 01 '22 at 07:50

2 Answers2

2

You could keep a map with the ids that you already added, and only add it if the key is missing:

const ids = {};

users.forEach(user => {
 if (!ids[user.id]) {
  someArray.push(user);
  ids[user.id] = true;
 }
})
Radu Diță
  • 13,476
  • 2
  • 30
  • 34
-1

using reduce would work for your case

let users = [{
    id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'John Doe',
    age: 50,
  },
  {
    id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'Jane Doe',
    age: 45,
  },
  {
    id: '8c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'Jane Doe',
    age: 45,
  },
];

var result = users.reduce((prev, curr) => {
  if (prev.find(i => i.id == curr.id)) return prev
  return [...prev, curr]
}, [])

console.log(result);
freedomn-m
  • 27,664
  • 8
  • 35
  • 57
Paul Wanjohi
  • 119
  • 9
  • I am getting an error which says **Cannot read properties of undefined (reading 'find')** – Kunal Tanwar Mar 01 '22 at 07:32
  • I've converted the above to a snipper - you can see it running fine here. There's no `find` in this code, so you're doing something else. – freedomn-m Mar 01 '22 at 07:34