2

I have two arrays:

  1. myFriends = [ 0: { uid: 123abc }, 1: { uid:456def }, ];
  2. theirFriends = [ 0: { uid: 123abc }, 1: { uid:789ghi }];

Now I want to see if the theirFriends array has an object with the same uid as as an object in the myFriends array and if it does, then set theirFriends[object].isFriend = true; if it doesn't, then set it to false instead.

so it should run through and ultimately set theirFriends[0].isFriend = true. and theirFriends[1].isFriend = false

So the new theirFriends array should be:

theirFriends = [ 0: { uid: 123abc, isFriend: true }, 1: { uid: 789ghi, isFriend: false }];

I have tried: .some(), .map(), .filter(), .forEach(), but I have yet to find a solution that works, but doesn't continously run everytime the object is updated with the new value.

4 Answers 4

1

First, you can convert your friend's list to a Set. Sets contain only unique values and it's fast to check if a value is included. Then, you can map over theirFriends and add the new property.

const myFriendSet = new Set(myFriends.map( friend => friend.uid ))
theirFriends = theirFriends.map( friend => ({
    uid: friend.uid,
    isFriend: myFriendSet.has(friend.uid)
})
Sign up to request clarification or add additional context in comments.

Comments

0

hi this is what i came up with

var myF = [ { uid: "123abc" }, { uid: "456def" } ];
var theirF = [ { uid: "123abc" }, { uid: "789ghi" }]
//loop through all their friends
for(var i = 0; i < theirF.length; i++)
{
    //loop through all my friends for comparison
    for(var j = 0; j < myF.length; j++)
    {
        if(!theirF[i].isFriend) //if isFriend is not set 
            theirF[i].isFriend = theirF[i].uid == myF[j].uid; //set current theirFriend isFriend propery
    }
}

Comments

0

Lodash _.isEqual is great for comparing objects.

Comments

0

Here is the oneliner using forEach and some:

theirFriends.forEach(tf => tf.isFriend = myFriends.some(mf => mf.uid === tf.uid));

Example:

myFriends = [{uid: '123abc'}, {uid:'456def'}, {uid: '789abc'}, {uid:'789def'}];
theirFriends = [{uid: '123abc'}, {uid:'789ghi'}, {uid: '789def'}, {uid:'000ert'}];

theirFriends.forEach(tf => tf.isFriend = myFriends.some(mf => mf.uid === tf.uid));

console.log(theirFriends);

Comments

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.