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

217
Vistas
Only push the object which is not in the array yet

This is my function:

const multiSelect = value => {
    let tmpArr = [...selectedPeople];

    if (tmpArr.length === 0) {
      tmpArr.push(value);
    } else {
      tmpArr.map(item => {
        if (item.id !== value.id) {
          tmpArr.push(value);
        } else {
          return;
        }
      });
    }
    setSelectedPeople(tmpArr);
  };

I want to check the array for the new value by comparing it with all items. If value === item item the loop function should return, but if the value is not in the array yet, it should push it.

This is a big problem for me but I assume it is a small problem for you guys.

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

0

Use Array.every() to check if the array doesn't contain an item with the same id:

const multiSelect = value => {
  const tmpArr = [...selectedPeople];
  
  if(tmpArr.every(item => item.id !== value.id)) {
    tmpArr.push(value);
  }

  setSelectedPeople(tmpArr);
};

However, this means that you're duplicating the array needlessly, while causing a re-render, that won't do a thing. So check if the item is already a part of selectedPeople by using Array.some(), and if it does use return to exit the function early. If it's not continue with cloning, and updating the state:

const multiSelect = value => {
  if(tmpArr.some(item => item.id === value.id)) {
    return;
  }

  const tmpArr = [...selectedPeople];
  
  tmpArr.push(value);

  setSelectedPeople(tmpArr);
};
about 4 years ago · Juan Pablo Isaza Denunciar

0

Use find to check if the item is already in the array. Also, there's no need to make a copy of the source array:

const multiSelect = value => {
    if (!selectedPeople.find(item => item.id === value.id))
        setSelectedPeople(selectedPeople.concat(value))
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Another approach.

const
    multiSelect = value => setSelectedPeople([
        ...selectedPeople,
        ...selectedPeople.some(({ id }) => id === value.id)
            ? []
            : [value]
    ]);
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