I have this array of reactions where every user is allowed to have only one reaction per message:
const reactions = [
{
id: "c9c5a273-6033-4239-a6f4-09c067633680",
profile: {
first_name: "Pete",
id: "1",
},
reaction_type: "love",
},
{
id: "2e94ee98-7d84-49c5-ac69-600a76d90012",
profile: {
first_name: "Eve",
id: "3",
},
reaction_type: "love",
},
{
id: "2e94ee98-7d84-49c5-ac69-600a76d90013",
profile: {
first_name: "Brad",
id: "4",
},
reaction_type: "thumbs_up",
},
{
id: "30511fa3-3574-44f4-93f0-04ee35edc62b",
profile: {
first_name: "John",
id: "2",
},
reaction_type: "lol",
},
{
id: "30511fa3-3574-44f4-93f0-04ee35edc62b",
profile: {
first_name: "Bill",
id: "5",
},
reaction_type: "thumbs_up",
},
];
Since there could be duplicate reaction_type, I want to keep only "my" reaction, eg. I'm user with id:4 and then remove duplicates of all the other reactions. I don't care witch user will be removed from the array.
Right now I'm using this logic:
const uid = "4";
const uniqueReactions = () => {
const myReactions = [];
reactions.forEach((item) => {
if (item.profile.id === uid) {
myReactions.push(item);
}
});
if (myReactions.length) {
const uniques = reactions
.filter((reaction) => {
return (
reaction.reaction_type !== myReactions[0].reaction_type &&
reaction.profile.id !== uid
);
})
.reduce(
(r, i) =>
!r.some(
(j) => i.reaction_type === j.reaction_type && i.profile.id !== uid
)
? [...r, i]
: r,
[]
);
return [...myReactions, ...uniques];
} else {
return reactions.reduce(
(r, i) =>
!r.some((j) => i.reaction_type === j.reaction_type) ? [...r, i] : r,
[]
);
}
};
Is there a better way on handling this? It feels messy and noisy.
Edit: just for clarity, I want to keep "my" reaction so I can highlight it with a different color in the UI.
'4'(the OP) appears more than just once within thereactionitems with anotherreaction_typethan just'thumbs_up'? Should all other reaction items be ignored likewise?reactionitem'sidvalue?reaction_type, so if a message has 10loveand 5thumb_upit will only show 1 heart and 1 thumb up icon. Hope this covers what you asked. Edit: my reaction will be highlighted in a different color than the others.message_id.