I have an array of objects that is basically like this.
const characters = [
{
id: 1
name: batman
biography: {
born-in: gotham
good-or-bad: good
}
stats: {
strength: 85
speed: 90
intelligence: 95
}
}
{
id: 2
name: superman
biography: {
born-in: krypton
good-or-bad: good
}
stats: {
strength: 90
speed: 85
intelligence: 80
}
}
{
id: 3
name: joker
biography: {
born-in: gotham
good-or-bad: bad
}
stats: {
strength: 70
speed: 95
intelligence: 100
}
}
]
Then, after mapping and displaying the objects in my page, I add a button that allows the user to mark the character as a favorite. The user can only add up to 6 favorites.
const [favorites, setFavorites = useState([]);
const addFavorite = () => {
favorites.length === 6 ?
console.log("favorites' list is full!") :
setFavorites(favorites.concat(character))
}
{characters.map((character)=>{
const {props} = character;
return (
<div>{props}</div>
<button onClick={addFavorite}>add to favorites</button>
);
})}
Now, what I want to do (and I don't know how to, after many attempts)
- preventing the user to add the same character twice to favorites. (I have tried with
favorites.contains(character)? or favorites.contains({character})?
but it didn't work.) - if the character is already a favorite, make the button change to a button that removes the favorite instead (changing both the function and the button text.)(I have no idea how to do this).
- Make an average score of all favorites' each stat. (For example, with your chosen favorites your average speed is xxx and your average strength is xxx).
- Last, but not least, favorites list must have up to 3 good characters and 3 bad characters. So, if the good or bad characters in the favorites' list are already 3, user cannot choose another good or bad character as favorite. I also don't know how to proceed with this one.
I'm working in a school project and I found my way through most of it, but I realise I still have things to learn, mostly about object props and how to access to them. Thank you. If anything is not clear, please say so and I will add the required data.