0

I am creating an app that gives rewards to the users, so they can obtain randomly complements to their avatars. I have a list of items that they can win and another list of items that they already have. My problem is that I don't know how to look for a match between the two arrays and create another without the ones that they already have.

var availableAvatar =['Csimple','Calien','Ccosmonaut','CgreenAereal','ChappyBirthday']
var userAvatars=['Ccosmonaut','ChappyBirthday']

I tried with the filter method but it creates an array of the matches and I don't know how to do it the other way. What I need:

var possibleAward=['Csimple','Calien','CgreenAereal']
var random = avatarP[Math.floor(Math.random() * possibleAward.length)];

Thank you very much.

  • https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items – chhil Aug 09 '21 at 12:03
  • Does this answer your question? [Remove same Values from array of Object](https://stackoverflow.com/questions/60708097/remove-same-values-from-array-of-object) – Najam Us Saqib Aug 10 '21 at 08:00

2 Answers2

0

var availableAvatar =['Csimple','Calien','Ccosmonaut','CgreenAereal','ChappyBirthday']
var userAvatars=['Ccosmonaut','ChappyBirthday']

var possibleRewards = availableAvatar.filter(element => {
  return !userAvatars.includes(element);
});

console.log(possibleRewards);
attempt0
  • 639
  • 5
  • 14
0

The array filter function is perfect for this:

var availableAvatars = ['Csimple','Calien','Ccosmonaut','CgreenAereal','ChappyBirthday']
var userAvatars = ['Ccosmonaut','ChappyBirthday']
var possibleAvatars = availableAvatars.filter(x => !userAvatars.includes(x));
var randomAvatar = possibleAvatars[Math.floor(Math.random() * possibleAvatars.length)];

console.log(possibleAvatars);
console.log(randomAvatar);
Robson
  • 2,008
  • 2
  • 7
  • 26