Alfrex92
Alfrex92

Reputation: 6768

Compare Two Arrays Of Objects and return a new array if value is true in Javascript

I need to compare 2 arrays

const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
]

An if invited is true I need to return a new array.

Something like this:

const newArray = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  },
]

Any idea how can I achieve this? Help please 😢

Upvotes: 0

Views: 41

Answers (3)

since you also need the !invited row, so the logic is to replace the same data from invitedFriends to allFriends (compare by id)

we loop on the allfriends then find if allfriend(n).id found on invitedFriend if found then push invitedFriend(found) if not just push the allfriend(n)

so in one line you can use

let x = allFriends.map( af =>  inviteFriends.find( x => x.userId === af.userId) || af );

Upvotes: 0

David Kabii
David Kabii

Reputation: 660

Use filtering to achieve that:

invitedFriends = allFriends.filter(friend => friend.invited==true);

Upvotes: 0

kyun
kyun

Reputation: 10264

const inviteFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: true
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: true
  }
]

const allFriends = [
  {
    userId: 'u12p3',
    name: 'Goku',
    invited: false
  },
  {
    userId: 'ufisj',
    name: 'Goten',
    invited: false
  },
  {
    userId: 'uefi3',
    name: 'Vegeta',
    invited: false
  },
];

const newArr = allFriends.map((friend) => {
  const found = inviteFriends.find((invited) => {
    return invited.userId === friend.userId
  });
  return {...friend, ...found};
});

console.log(newArr);

Upvotes: 1

Related Questions