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 user.id is contained in an array of objects in Javascript?

I am trying to check if a user (preferrably the id) is contained in an array of users, i am getting some issues when i try doing it this way

if (
  res.data.followers.includes(id=1)
){
    setIsFollow(true);
    console.log("user exists");
}

This is array

[
    {id: 1, username: 'destiny', email: 'desphixs@gmail.com'},
    {id: 2, username: 'flourish', email: 'flourish@gmail.com'},
]

i want to check if, for example, user with id 2 exists in the array, then conlog ‘user exists’;.

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

>Solution :

You can do this. Here filter will return an array containing a single object that matches the id. Then you can check the length of the array, which should be equal to 1.

if(res.data.followers.filter(obj => obj.id === 1).length === 1) {
  // logic
}
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