0

I'm trying to determine if two arrays (a and b in the code below) are identical.

I've written the code below, but the for loop breaks after it returns a 'true' value for any array element.

 function arraysEqual(a, b) {
     if (a === b) return true;
     for (var i = a.length; i--;) {
         if (a[i] !== b[i]) return false;
     }
     return true;
 }

I think that I need to run an every() function but I can't figure out how to define the function to check identity between the arrays.

Thank you in advance.

Rahul
  • 18,271
  • 7
  • 41
  • 60
S. D.
  • 1
  • 1
  • 2

2 Answers2

0

You can use

function arraysEqual(a, b) {
if(a.length !== b.length)
    return false;
for(var i = a.length; i--;) {
    if(a[i] !== b[i])
        return false;
}

return true;

}

or

a.toString() == b.toString()
  • The `toString()` method may not work in a lot of cases, for instance `[''].toString() == [].toString()` – Ulysse BN Feb 09 '17 at 06:12
0

Try this function,

function arraysEqual(a, b) {
if (a === b) return true;
for (var i = a.length-1; i>=0;i--) {

if (a[i] !== b[i]) return false;
}
return true;
}
user3386479
  • 51
  • 2
  • 8