Tengo esta serie de reactions donde a cada usuario se le permite tener solo una reacción por mensaje:
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", }, ]; Dado que podría haber un tipo de reaction_type duplicado, quiero mantener solo "mi" reacción, por ejemplo. Soy un usuario con id:4 y luego elimino los duplicados de todas las demás reacciones. No me importa que el usuario sea eliminado de la matriz.
En este momento estoy usando esta lógica:
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, [] ); } };¿Hay una mejor manera de manejar esto? Se siente desordenado y ruidoso.
Editar : solo para mayor claridad, quiero mantener "mi" reacción para poder resaltarla con un color diferente en la interfaz de usuario.
Creo que lo que más lo complica es el uso abundante de nombres de variables ternarias y de una letra.
Dicho esto, creo que podría ser más sencillo. Aquí está mi intento de hacerlo:
function getUniqueReactions(id, reactions) { const userTypes = reactions .filter(reaction => reaction.profile.id === id) .map(reaction => reaction.reaction_type); const processedTypes = []; return reactions.reduce((accumulator, curItem) => { const { reaction_type: curType } = curItem; // The current type // If the current user has posted this type but this isn't the current user, skip the item if (userTypes.includes(curType) && curItem.profile.id !== id) { return accumulator; } // Check if either we're the supplied user and the type matches // or this is a reaction type the user hasn't posted and we haven't seen yet if (curItem.profile.id === id || !processedTypes.includes(curType)) { accumulator.push(curItem); processedTypes.push(curType); } return accumulator; }, []); } console.log(getUniqueReactions("4", reactions));