Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
Why is my conditional function of adding an item from an array to another one not working?

Basically I have an array called "Heroes" and through buttons I'm trying to add or delete certain items from that array to another one called "favorites". When adding a hero to favorites, the message "item added to favorites!" appears, but the part in which I display my favorites in the document appears to show a blank space instead of the hero's name like I want to. Also, the part of showing "item already added" or "favorites list full" doesn't work. Also, when trying to add more than a hero to favorites, it doesn't allow me to. I don't know what I'm doing wrong. The "clear favorites" button works just fine, and the "remove favorite" appears to do so as well.

´´´

  const [favorites, setFavorites] = useState([]);
  const [message, setMessage] = useState("");

const addToFavorites = (id) => {
  if (favorites.includes((heroin) => heroin.id === id)){
    setMessage("hero already in favorites!")
  } if (favorites.length = 6) {
    setMessage("favorites list full!")
  }
    const newFavorites = favorites.concat(heroin => heroin.id === id)
    setFavorites(newFavorites)
    setMessage("item added to favorites!")
  }

const deleteFavorite = (id) => {
 const newFavorites = favorites.filter((heroin) => heroin.id !== id)
 setFavorites(newFavorites);
 setMessage("");
}

 {heroes.map((heroin)=>{
      const {id, props} = heroin;
      return <div key={id}><h1>{props}</h1></div>;
})

<button onClick={clearFavorites}>Clear favorites</button>
 <button value={id} onClick={()=>addToFavorites(id)}>
            Add to favorites</button>
            <button value={id} onClick={()=> deleteFavorite(id)}>remove favorite</button>
        <h4>{message}</h4>

{favorites.map((favorite)=>{
      const {name} = favorite;
      return (
        <div>
          <h1>{name}</h1>
          </div>
      )
    })}

´´´

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Issues

You are calling array functions that don't take callbacks.

  • Array.prorotype.includes takes a value, not a predicate function. Since the favorites array doesn't have an exact strictly equal version of the (heroin) => heroin.id === id) function, false is returned because no element can match.
  • Array.prototype.concat will add whatever the value is that is passed to to a new copy of the array and return the array.
  • favorites.length = 6 is attempting to assign a value to the length property.

Code:

const addToFavorites = (id) => {
  if (favorites.includes((heroin) => heroin.id === id)) { // Always false!
    setMessage("hero already in favorites!");
  }
  if (favorites.length = 6) {
    setMessage("favorites list full!");
  }
  const newFavorites = favorites.concat(heroin => heroin.id === id); // only adds function instead of hero object
  setFavorites(newFavorites);
  setMessage("item added to favorites!");
}

Solution

  • Use Array.prototype.find to search the array for a specific value using a predicate function.
  • Concatenate the found element if not already contained in array.

Code:

const addToFavorites = (id) => {
  const hero = favorites.find((heroin) => heroin.id === id);

  if (hero) {
    setMessage("hero already in favorites!");
  } else {
    if (favorites.length === 6) {
      setMessage("favorites list full!");
    } else {
      setFavorites(favorites => favorites.concat(hero));
      setMessage("item added to favorites!");
    }
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda