Skip to content

Instantly share code, notes, and snippets.

@AbelVM
Last active November 21, 2025 13:08
Show Gist options
  • Select an option

  • Save AbelVM/1d2d419519078446f90980ec594c6e7c to your computer and use it in GitHub Desktop.

Select an option

Save AbelVM/1d2d419519078446f90980ec594c6e7c to your computer and use it in GitHub Desktop.
Light fast array comparison in JavaScript

Light fast array comparison in JavaScript

This simple method will ease your ID arrays (no element repetition) equality checks.

If you don't care about array order, you will find a great performance improvement when compared with any other approach.

Parameters

  • that: 2nd array to be compared with.
  • ordered: optional boolean (default: true) to take into account the order of the array elements.

Code

function aEquals(that, ordered = true){
    if (this.length != that.length){
      return false;
    }else{
      if(ordered){
        return this.toString() == that.toString();
      }else{
        return (new Set(this)).symmetricDifference(new Set(that)).size == 0
      }
    }
}
Array.prototype.equals = aEquals;

Examples

const
  a = [1,2],
  b = [1,2,3],
  c = [2,1],
  d = [1,3];

a.equals(a);
//> true
a.equals(b);
//> false
a.equals(c);
//> false
a.equals(d);
//> false

a.equals(a, false);
//> true
a.equals(b, false);
//> false
a.equals(c, false);
//> true
a.equals(d, false);
//> false

Why the Set stuff

While it looks that, for unsorted comparision,

this.sort().toString() == that.sort().toString()

would be more straightforward and fast... That might be true when both arrays are quite small.

Sorting is expensive!! (O(n log n))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment