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

85
Visualizações
Create new array based on comparison between two array of objects

Suppose I have two array of Object as,

let oldBookDetails = [
    {'name':'Harry pottar','amount':10, is_modified: false},
    {'name':'LOTR','amount':20, is_modified: false},
    {'name':'dune','amount':15, is_modified: false}
]

let newBookDetails = [
    {'name':'Harry pottar','amount':15},
    {'name':'LOTR','amount':20},
    {'name':'HR','amount':15}
]

let bookModified = []

I want to create new array of Object by comparing newBookDetails with oldBookDetails,

and check if any name is removed newDetails, don't push into the bookModified array,

if amount has been changed then push newBookDetails object into bookModified with is_modified: true and if newBookDetails amount is same push into bookModified array with is_modified:false.

For this I tried as:

newBookDetails.forEach((el) => {

    oldBookDetails.forEach((ele) => {

        if(Object.values(el).indexOf(el.name) > -1) {
            if(el.amount === ele.amount) {
                bookModified.push(el)
            }else if(el.amount != ele.amount) {
                el.is_modified = true
                bookModified.push(el)
            }
        } else if(Object.values(el).indexOf(el.name) === -1) {
            //this loops as all are not equal....i am stuck from this part.
        }
    })
})

Expected O/P :

console.log(newBookDetails)

[
    {'name':'Harry pottar','amount':15, is_modified: true},
    {'name':'LOTR','amount':20, is_modified: false},
    {'name':'HR','amount':15, is_modified: true}
]

If anyone needs any further information please do let me know.

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

0

You can do it using map() and find():

map() on the second array and try to find the book in the first one using property name. If not found pass in modified true, else check the amount and pass modified value accordingly.

let oldBookDetails = [
  { 'name': 'Harry pottar', 'amount': 10, is_modified: false },
  { 'name': 'LOTR', 'amount': 20, is_modified: false },
  { 'name': 'dune', 'amount': 15, is_modified: false }
];

let newBookDetails = [
  { 'name': 'Harry pottar', 'amount': 15 },
  { 'name': 'LOTR', 'amount': 20 },
  { 'name': 'HR', 'amount': 15 }
];

let bookModified = newBookDetails.map((x) => {
  let foundBook = oldBookDetails.find(old => old.name === x.name);
  if (foundBook) {
    if (foundBook.amount !== x.amount)
      return { ...x, is_modified: true };
    else
      return { ...x, is_modified: false };
  }
  else
    return { ...x, is_modified: true };
});
console.log(bookModified);

about 4 years ago · Juan Pablo Isaza Relatório

0

Array.map will help you to generate the new array as per your requirement.

Logic

  • Loop through newBookDetails array.
  • Check if node from newBookDetails is present in oldBookDetails
  • If no return the newBook node with is_modified as true
  • If yes. return the node with is_modified value as a boolean that compare the new book and old book price.
  • To find the removed book, filter the oldBookDetails array and check nodes that are not prtesent in newBookDetails

const oldBookDetails = [ {'name':'Harry pottar','amount':10, is_modified: false}, {'name':'LOTR','amount':20, is_modified: false}, {'name':'dune','amount':15, is_modified: false}];
const newBookDetails = [ {'name':'Harry pottar','amount':15}, {'name':'LOTR','amount':20}, {'name':'HR','amount':15} ];
const bookModified = newBookDetails.map((node) => {
  const oldBookNode = oldBookDetails.find((item) => item.name === node.name);
  if (oldBookNode) {
    return { ...node, is_modified: oldBookNode.amount !==  node.amount }
  } else {
    return { ...node, is_modified: true };
  }
});
const removedBooks = oldBookDetails.filter((book) => !newBookDetails.find((node) => node.name === book.name));
console.log(bookModified);
console.log(removedBooks);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do with below snippet

newBookDetails.forEach(newBook => {
  let found = false;
  oldBookDetails.forEach(oldBook => {
    if (oldBook.name === newBook.name) {
      if (oldBook.amount === newBook.amount) {
        bookModified.push({
          'name': newBook.name,
          'amount': newBook.amount,
          is_modified: false
        })
      } else {
        bookModified.push({
          'name': newBook.name,
          'amount': newBook.amount,
          is_modified: true
        })
      }
      found = true;
    }
  })
  if (!found) {
    bookModified.push({
      'name': newBook.name,
      'amount': newBook.amount,
      is_modified: true
    })
  }
})
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