Search code examples
javascriptarrayscomparisoncompare

Javascript Arrays - Checking two arrays of objects for same contents, ignoring order


I have two JavaScript arrays (A and B) that contain objects that I created. I want to check that all the objects in array A are contained in array B, but not necessarily in the same order.

What is the best way to do this?

Edit:

They are all actual objects, not primitives, so I will need to compare their contents and structure as well (maybe using something like JSON.stringify).

I want to do this because I'm learning Test-Driven Development, and I want to test functions that return lists of objects. I need to test whether the returned lists have the expected objects in them or not (order doesn't matter in this case).


Solution

  • Usage: isEqArrays(arr1, arr2)

    //
    // Array comparsion
    //
    
    function inArray(array, el) {
      for ( var i = array.length; i--; ) {
        if ( array[i] === el ) return true;
      }
      return false;
    }
    
    function isEqArrays(arr1, arr2) {
      if ( arr1.length !== arr2.length ) {
        return false;
      }
      for ( var i = arr1.length; i--; ) {
        if ( !inArray( arr2, arr1[i] ) ) {
          return false;
        }
      }
      return true;
    }