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

171
Visualizações
Filter array of dictionaries with array of dictionaries

I have two arrays of dictionaries, both contain an ID property, one is 'id' and the other is '_id'.

I am trying to filter an array that contains all books available, and grab data from it based on what books a user has.

const books = allbooks.filter(({ id }) =>
   userBooks.findIndex((book) => book._id === id)
)

This is the code I am using right now, but it's not doing what I expect.

What the data looks like

allbooks [
{ 
  id: 1,
  name: 'Book 1'
},
{ 
  id: 2,
  name: 'Book 2'
}
]

userBooks [
 { 
   _id: 1
}
]

Should I create an array from the 2nd array's _ids and filter with that? Trying to find the best practice way of doing this, I am using arrays of dictionaries a lot and find it tough sometimes.

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

0

You are sooo close my friend. The problem is Array.prototype.findIndex is returning the first index in which your lambda function returns true. The index of the matching book is index 0, which is falsy, which makes your filter ignore it because the result of the filter lambda function is false.

Instead, you can check if the result of your findIndex is > -1 since Array.prototype.findIndex returns -1 if the element is not found.

const allbooks = [
{ 
  id: 1,
  name: 'Book 1'
},
{ 
  id: 2,
  name: 'Book 2'
}
];

const userBooks = [
 { 
   _id: 1
}
];

const books = allbooks.filter(({ id }) =>
   userBooks.findIndex((book) => book._id === id) > -1
)

console.log(books);

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