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

113
Vistas
Compare each item in an array of objects

I have an array of objects:

   const array = [{ 
    "colour": "red",
    "job": "student",
    "title": "Mr",
},
 {​
    "colour": "green",
    "job": "student",
    "title": "",
},
{​
    "colour": "",
    "job": "teacher",
    "title": "Mr",
},  
{​
    "colour": "red",
    "job": "student",
    "title": "Mr",
}}]

I would like to compare the objects inside the array with each other.

What I have so far does not seem efficient as I would be comparing index i=1 and j=2 and i=2 and j=1 which is comparing exactly the same object. I am using Lodash _.isEqual() to compare the objects.

 const handleArrayItems = () => {
    for (let i = 0; i <= array.length; i++) {
        for (let j = 1; j < array.length; j++) {
            if (j === i) {
                continue; //to avoid comparing same object
            }
            if (_.isEqual(array[j],array[i])) {
                return true;
            }
        }
    }   
 };

Based on what is returned from above, it is passed into an if/else statement.

if (handleArrayItems()) {
  console.log("found a duplicate item in array")
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Separate objects are not equal to each other.

if (_.isEqual(array[j] === array[i])) {

will evaluate the argument first:

array[j] === array[i]

which is false, resulting in:

if (_.isEqual(false)) {

which doesn't work.

You need to pass both values to isEqual for comparison

if (_.isEqual(array[j], array[i])) {

so that Lodash can compare the values itself.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Make j goes from i+1 to array.length to doing comparison twice.

And i can go to length-1 only, since j will go to the end.

for (let i = 0; i <= array.length-1; i++) {
    for (let j = i+1; j < array.length; j++) {
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