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()))
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.
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);