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

137
Visualizações
Check if ID Is Found Another Array in ES6

I wanted to filter out the data. I wanted to check if data on data1 is found on data2 and to check if it has errorMessages. Please check my code below. Is there a better way to do it?

data1

[
    {
        "ids": "0111",  
    },
    {
        "ids": "0222",
    },
    {
         "ids": "0333",
    }
]

data2

[
  {
    "id": "0111",
    "errorMessages": [
      {
        "message": ["sample error message 1"]
      }
    ]
  },
  {
    "id": "0333",
    "errorMessages": []
  }
]

Code

const output= data1.filter(
  (element) => element.ids === data2.find((data) => data).id
);

console.log("output", output);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

.find((data) => data) doesn't do anything useful - each item in the array is an object, which is truthy, so that'll always return the first element in the array.

If you did want to .find a matching element in the other array - then a better approach would be to make a Set of the IDs found in the other array first (Set lookup is much quicker - O(1) - than .find, which is O(n)).

You also need to implement the logic to check if the errorMessages is empty.

const data1 = [
    {
        "ids": "0111",  
    },
    {
        "ids": "0222",
    },
    {
         "ids": "0333",
    }
]
const data2 = [
  {
    "id": "0111",
    "errorMessages": [
      {
        "message": ["sample error message 1"]
      }
    ]
  },
  {
    "id": "0333",
    "errorMessages": []
  }
]


const ids = new Set(
  data2
    .filter(item => item?.errorMessages.length)
    .map(item => item.id)
);

const output= data1.filter(
  element => ids.has(element.ids)
);
console.log("output", output);

about 4 years ago · Juan Pablo Isaza Relatório

0

Without Set, but use Object as the map.


const IDKeys = {};

data2.forEach(data => {
    if (data.errorMessages.length){
       IDKeys[data.id] = true; // means valid 
    }
})


const filteredArray = data1.filter(data => IDKeys[data.id]);

This would be only O(n) since accessing key on object is O(1)

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