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

225
Visualizações
Inlining an array comparison function

Let's say I have the following array comparison function:

function cmp_arrs(a, b) {
    if (a === b) return true;
    if (a.length != b.length) return false;
    for (let i=0; i < a.length; i++)
        if (a[i] != b[i]) return false;
    return true;
}

How could I convert this -- particular the for loop -- into a single-line javascript Arrow function. So far I have:

const cmp_arrs2 = (a,b) => (a === b) || ((a.length === b.length) && (<forLoop?>))

My current approach is stringifying it and seeing if that works but that seems a bit crude/wrong:

const cmp_arrs2 = (a,b) => (a === b) || ((a.length === b.length) 
      && (Object.values(a).toString() == Object.values(b).toString()))
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use a higher-order function such as .every(). In order for .every() to return true, the callback must return true for each item, if it returns false for any item then .every() will result in false. You can use the second argument of the callback to obtain the index i to grab the corresponding element from the array b:

const cmp_arrs2 = (a,b) => 
  a === b || a.length === b.length && a.every((elem, i) => elem === b[i]);

&& has higher operator precedence than ||, so the grouping () can also be omitted if you want.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can do something like the following:

// Create a Separate Function
const cmp_loop = (a, b) => {
for (let i=0; i < a.length; i++)
        if (a[i] != b[i]) return false;
 return true;
}

// Now make a single line function
const cmp_array = (a, b) => (a === b) || ((a.length === b.length) && cmp_loop(a, b))

// You can also do this:
const cmp_array_2 = (a, b) => (a === b) || ((a.length === b.length) && a.reduce((equal, current, index) => !equal ? equal : current === b[index], true))

// Another quick way (If you are sure that the elements in both arrays are on same positions or indexes):
const cmp_array_3 = (a, b) => JSON.stringify(a) === JSON.stringify(b);

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