1

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.

1
  • You could put the ids of the users, that are followed by at-least one other user, in a Map and then just iterate over the data array and see if the current user's id is in that Map or not. It is more efficient than taking one user id and then searching for it in the following array of other user objects in the data array Commented Sep 8, 2020 at 12:16

1 Answer 1

3

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)
 );
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I completely forgot about filter() method. Thanks again !

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.