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

152
Visualizações
How to make a javascript comparison more concise?

Consider the following two javascript objects:

Object A:

{
  specialPropertyA: string,
  partTime: boolean,
  role: { key: string, label: string }
}

Object B:

{
  specialPropertyB: string,
  partTime: boolean,
  role: { key: number, label: string }
}

Now, consider an arrayA: ObjectA[] and an arrayB: ObjectB[].

I am looking for a concise way to determine:

If any of the ObjectA's have partTime === true AND role.key === 1, are there any ObjectBs, which fulfill the same requirements? I want to check the same for role.key === 2.

I know I could do sth like:

if(
    arrayA.filter(objectA => objectA.partTime === true && objectA.role.key === 1) 
    && arrayB.filter(objectB => objectB.partTime === true && objectB.role.key === 1) 
    || arrayA.filter(objectA => objectA.partTime === true && objectA.role.key === 2)
    && arrayB.filter(objectB => objectB.partTime === true && objectB.role.key === 2)
  )

But I don't like this solution at all, especially since I am repeating the same code for key 2. Any suggestions as on how to make this more concise?

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

0

One way would be to make a higher-order function that you can pass the key number you want to find.

Also, because partTime is a boolean, obj.partTime === true simplifies to obj.partTime.

const makeCb = keyNum => obj => obj.partTime && obj.role.key === keyNum;

if (
  (arrayA.some(makeCb(1)) && arrayB.some(makeCb(1))) ||
  (arrayA.some(makeCb(2)) && arrayB.some(makeCb(2)))
) {

You'll want .some (or .find, if you want to put the result into a variable). .filter won't work in an if because even if there are no results, empty arrays are truthy.

about 4 years ago · Juan Pablo Isaza Relatório

0

If your arrays have many possible key values, which could match, then maybe first collect the found key values in the first array before scanning the second:

const keysA = new Set(arrayA.map(({partTime, key}) => partTime && key));
if (arrayB.some(({partTime, key}) => partTime && keysA.has(key))) {
  /* ... */
}

This assumes that false is not a possible value of key.

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