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()))
CodePudding user response:
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.
CodePudding user response:
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))