Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda