Rakonjac
Rakonjac

Reputation: 87

JavaScript (ReactJS) comparing two Objects

I have an object with users:

const data = [
{
  name: "John",
  lastName: "Doe",
  email: "[email protected]",
  password: "123",
  following: [{ id: "113"}, { id: "111" } }],
  id: "112",
},
{
  name: "Jane",
  lastName: "Doe",
  email: "[email protected]",
  password: "123",
  following: [{ id: "112" }],
  id: "113",
},
{
  name: "Mark",
  lastName: "Twain",
  email: "[email protected]",
  password: "123",
  following: [],
  id: "111",
},
];

As you can see all users have an array named "following", and that array contains id's of users which the user follows. I want to access that array "following" to find out which users are not followed. Let's say that we want to check the "following" array of the first user John Doe with id="112".

 const followers = [];
 let suggestions = null;

 props.users.forEach((user) => {
   if (user.id === '112') {
     user.following.forEach((item) => {
     followers.push(item);
    });
  }
 });

 followers.map((item) => {
   suggestions = props.users.map((user) => {
     if (user.id !== item.id && user.id !== '112) {
       console.log(item.id); 
       return <div>something</div>;
     }
   });
 });

I tried something like this, but the result is not what i expected to be. As i said, i want to return users that are not followed and render them because i want them to be visible so the user can follow them. I hope that i was understandable enough. Thanks.

Upvotes: 1

Views: 66

Answers (1)

Dylan Kerler
Dylan Kerler

Reputation: 2187

It's a negative comparison. So you want to filter out all users that a user IS following. You can loop through each user and compare it against the following array. If the following array contains the user then don't show it.

 const notFollowing = allUsers.filter(user => 
     !currentUser.following.some(({ id }) => id === user.id)
 );

Upvotes: 3

Related Questions