0

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 😢

2
  • Seems simple enough. Where are you stuck? Commented Jun 2, 2020 at 2:24
  • And why use arrays? If you have unique identifiers, arrays seem like a strange choice. Commented Jun 2, 2020 at 2:25

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

Use filtering to achieve that:

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

Comments

0

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

1 Comment

Please add some explanation to your answer such that others can learn from it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.