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

105
Visualizações
filter array based on ObjectId

So I have 2 arrays here, let say

const users = [{_id:ObjectId("6274fb5b82bcc9b2ccc0a361"), name:p1, age:10}, 
               {_id:ObjectId("6274fbc382bcc9b2ccc0a362"), name:p2, age:15},
               {_id:ObjectId("6277a3d5b66c061096222bbd")}, name:p3, age:20];

const filterArray = [ObjectId("6274fbc382bcc9b2ccc0a362"),ObjectId("6277a3d5b66c061096222bbd")];

I want to filter result based on matching ObjectId, here's what I'm trying to do

const filteredUsers = users.filter(user=> !!filterArray.includes(user._id));

I'm expecting this result

filteredUsers = [{_id:ObjectId("6274fbc382bcc9b2ccc0a362"), name:p2, age:15},
                 {_id:ObjectId("6277a3d5b66c061096222bbd")}, name:p3, age:20]
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try to map the filterArray to an array of Strings and use that for comparison:

const filterArray = [ObjectId("6274fbc382bcc9b2ccc0a362"),ObjectId("6277a3d5b66c061096222bbd")];
const mappedFilterArray = filterArray.map(id => id.toString());

const filteredUsers = users.filter(user=> !!mappedFilterArray.includes(user._id.toString()));
about 4 years ago · Juan Pablo Isaza Relatório

0

You must convert it to string then filter it:

const users = [
  { _id: ObjectId('6274fb5b82bcc9b2ccc0a361'), name: 'p1', age: 10 },
  { _id: ObjectId('6274fbc382bcc9b2ccc0a362'), name: 'p2', age: 15 },
  { _id: ObjectId('6277a3d5b66c061096222bbd'), name: 'p3', age: 20 }
]

const filterArray = [
  ObjectId('6274fbc382bcc9b2ccc0a362'),
  ObjectId('6277a3d5b66c061096222bbd')
]
const stringFilterArray = filterArray.map(item => item.toString())
const filteredUsers = users.filter(user => stringFilterArray.includes(user._id.toString()))
/* result
[
  { _id:ObjectId("6274fbc382bcc9b2ccc0a362"), name:p2, age:15 }, 
  { _id:ObjectId("6277a3d5b66c061096222bbd"), name:p3, age:20 }
]
*/
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