Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda