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

301
Vistas
How to check if an object exists in an *empty* Array

I have an empty array

const someArray = []

and then I have another array of 2 objects (can vary)

let users = [
    {
        id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
        name: 'John Doe',
        age: 50,
    },
    {
        id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
        name: 'Jane Doe',
        age: 45,
    },
];

the id key which make users unique.

As you can see I have 2 users with same id I only want to add the first one. What I did so far

users.forEach((user) => {
  if (!someArray.includes(user.id)) {
    someArray.push(user);
  }
});

// OTHER METHOD I USED
users.forEach((user) => {
  if (someArray.some((element) => element.id !== user.id)) {
    someArray.push(user);
  }
});

The first method appending both elements even thier id's are same and the second method is doing nothing or is not appending anything.

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

0

You could keep a map with the ids that you already added, and only add it if the key is missing:

const ids = {};

users.forEach(user => {
 if (!ids[user.id]) {
  someArray.push(user);
  ids[user.id] = true;
 }
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

using reduce would work for your case

let users = [{
    id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'John Doe',
    age: 50,
  },
  {
    id: '2c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'Jane Doe',
    age: 45,
  },
  {
    id: '8c919536-ccb5-4c3b-b599-36dc716b7478',
    name: 'Jane Doe',
    age: 45,
  },
];

var result = users.reduce((prev, curr) => {
  if (prev.find(i => i.id == curr.id)) return prev
  return [...prev, curr]
}, [])

console.log(result);

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