Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!