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

151
Visualizações
How can I filter the array of objects by: if object ids are consective

I have a JSON file with data inside. I have to filter the data by : if user has more than two names, and if user ids are consecutive. The JSON file :

[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden@xerex.com",
"nameList": [
  {
    "id": 0,
    "name": "Wendi Mooney"
  },
  {
    "id": 2,
    "name": "Holloway Whitehead"
  }
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
  {
    "id": 0,
    "name": "Janine Barrett"
  },
  {
    "id": 1,
    "name": "Odonnell Savage"
  },
  {
    "id": 2,
    "name": "Patty Owen"
  }
]
}, ...

I have managed to find an a solution to filter if the users have more than two names : userData.filter((names,i) => { return names?.nameList?.filter(names => { return names.name;}).length > 2 ; }) But I cant seem to grasp myself around the concept of filtering the consecutive ids. Also I was advised to not use any for loops at all. Only ES6 array loops like map, forEach and filter.

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

0

Here's a solution that uses every() to compare the ID of every element with the previous ID:

const result = data.filter(({nameList}) =>
  nameList.length > 2 &&
  nameList.every(({id}, i, a) => !i || id === a[i - 1].id + 1)
);

Complete snippet:

const data = [{
  "_id": "62bd5fba34a8f1c90303055c",
  "index": 0,
  "email": "mcdonaldholden@xerex.com",
  "nameList": [{
    "id": 0,
    "name": "Wendi Mooney"
  }, {
    "id": 2,
    "name": "Holloway Whitehead"
  }]
}, {
  "_id": "62bd5fbac3e5a4fca5e85e81",
  "index": 1,
  "nameList": [{
    "id": 0,
    "name": "Janine Barrett"
  }, {
    "id": 1,
    "name": "Odonnell Savage"
  }, {
    "id": 2,
    "name": "Patty Owen"
  }]
}];

const result = data.filter(({nameList}) =>
  nameList.length > 2 &&
  nameList.every(({id}, i, a) => !i || id === a[i - 1].id + 1)
);

console.log(result);

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