Kabiru Wahab
Kabiru Wahab

Reputation: 87

returning data efficiently in loop with java script

I recently fall in a loop pit when i tried to return data from a multi loop statement.

I am creating profile filtering system which after fetch people. It will filter the friends of the user.

 class UserFriend {

   analyseUserFriends(people, userfriends){
    people.forEach(person => {
        this.userfriends.forEach(friend => {
            if(person._id.toString() == friend._id.toString()){
                person.relationship = 0
            }else{
               person.relationship = 1;
             }
            return friend;//After loging friend the object of relationship is part of the member
        });
         return person;//After loging person the object of relationship is not part of the member
     });
  }
}

The data are from Mongo and it similar to this

     userfriends:[ 
    {friend: mongoId},
    {friend: mongoId},
    {friend: mongoId},
    {friend: mongoId},
];
people: [
    {_id: mongoId}, 
    {_id: mongoId}, 
    {_id: mongoId}, 
    {_id: mongoId},
    {_id: mongoId}, 
    {_id: mongoId}, 
    {_id: mongoId}, 
    {_id: mongoId}
];

Thanks.

Upvotes: 0

Views: 33

Answers (1)

Hammerbot
Hammerbot

Reputation: 16344

As @Leafyshark mentioned in his comment, this is a usecase for the map method. Combining with the find method, you should be able to achieve this:

function analyseUserFriends (people, userFriends) {
    return people.map(person => {
        person.relationship = userFriends.find(x => x.friend.toString() === person._id.toString()) ? 1 : 0
        return person
    })
}

Upvotes: 1

Related Questions