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

124
Visualizações
Compare two array of objects and return true if they are match

Let's say I have two array of objects as,

let detail1 = [
    {'book':'LOTR','price':'14'}
    {'book':'Harry pottar','price':'12'},      
]

let detail2 = [
    {'book':'Harry pottar','price':'15'},
    {'book':'LOTR','Price':'14'},
    {'book':'HPP','Price':'21'}
]

I want to compare two array of objects and return true or false depending on whether they are same or not.

Note: object's structure i.e. key will always be same, their value may or may not change.

For this I tried as,

for(let i = 0 ;i<detail1.length; i++){
    for(let j = 0; j<detail2.length; j++){
        if(JSON.stringify(detail1[i]) === JSON.stringify(detail2[i])){
            boolValue = true
        } else {
            boolValue = false
        }
    }
}

But this is giving incorrect value for let's say I have another array of object as,

let detail1 = [
    {'book':'LOTR','price':'14'}
    {'book':'Harry pottar','price':'12'},      
]

let detail2 = [
    {'book':'Harry pottar','price':'12'},
    {'book':'LOTR','price':'14'}
]

But when order is changed it's giving incorrect value.

What is the possible solution to compare two array of object and return true if they are same and false if different for any cases given the structure of object i.e. key is same.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can't use JSON encoding for checking the equality, because it's order dependent, eg.:

console.log(
  JSON.stringify({'book':'LOTR','price':'14'}) == JSON.stringify({'price':'14', 'book':'LOTR'})
)

However you can do something like this:

let detail1 = [
    {'book':'LOTR','price':'14'},
    {'book':'Harry pottar','price':'12'},      
]

let detail2 = [
    {'book':'Harry pottar','price':'15'},
    {'book':'LOTR','Price':'14'},
    {'book':'HPP','Price':'21'}
]

function equal(a, b){
  return a.length == b.length && // same length and
         a.every( // every element in a
            e1 => b.some( // has a match in b
               e2 => e1.book == e2.book && e1.price == e2.price
            )
         )
}
console.log(equal(detail1,detail2), equal(detail1,detail1), equal(detail2,detail2))

As @T.J Crowder pointed out, you can actually avoid checking every entry of your object manually and just use Object.entries (be aware of using this only if your objects are composed by only key pair strings)

let detail1 = [
    {'book':'LOTR','price':'14'},
    {'book':'Harry pottar','price':'12'},      
]

let detail2 = [
    {'book':'Harry pottar','price':'15'},
    {'book':'LOTR','Price':'14'},
    {'book':'HPP','Price':'21'}
]

function equal(a, b){
  return a.length == b.length && // same length and
         a.every( // every element in a
            e1 => b.some( // has a match in b
               e2 => Object.keys(e1).every(key => e1[key] === e2[key])
            )
         )
}
console.log(equal(detail1,detail2), equal(detail1,detail1), equal(detail2,detail2))

about 4 years ago · Juan Pablo Isaza Relatório

0

You can easily achieve the result using Object.keys and every

arr1.length !== arr2.length &&
    arr1.every((o, i) =>
      Object.keys(o).every((prop) => arr2[i][prop] && arr2[i][prop] === o[prop])
    )

let detail1 = [
  { book: "LOTR", price: "14" },
  { book: "Harry pottar", price: "12" },
];

let detail2 = [
  { book: "Harry pottar", price: "15" },
  { book: "LOTR", Price: "14" },
  { book: "HPP", Price: "21" },
];

function isEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) return false;
  return arr1.every((o, i) => {
    return Object.keys(o).every((prop) => {
      return arr2[i][prop] && arr2[i][prop] === o[prop];
    });
  });
}

console.log(isEqual(detail1, detail2));

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