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

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

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 Relatório

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 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