Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if an object exists in an *empty* Array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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;
 }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading