Jordan Benge
Jordan Benge

Reputation: 1135

Compare an array of objects to another array of objects

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.

Upvotes: 2

Views: 1236

Answers (4)

Kirill Simonov
Kirill Simonov

Reputation: 8481

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);

Upvotes: 0

Yossi
Yossi

Reputation: 6027

Lodash _.isEqual is great for comparing objects.

Upvotes: 0

dev.dmtrllv
dev.dmtrllv

Reputation: 71

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
    }
}

Upvotes: 0

LazyElephant
LazyElephant

Reputation: 484

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)
})

Upvotes: 1

Related Questions