Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare arrays of objects independent of the order

I have 2 arrays of objects and I have to compare them, but the order of the objects DOES NOT matter. I can't sort them because I won't have their keys' names because the functions must be generic. The only information that I'll have about the array is that both array's objects have the same amount of keys and those keys have the same name. So the array1 must contain the same objects as the array2.

var array1 = [{"key1":"Banana", "key2":"Yammy"}, {"key1":"Broccoli", "key2":"Ew"}];
var array2 = [{"key1":"Broccoli", "key2":"Ew"}, {"key1":"Banana", "key2":"Yammy"}];

In the example, array1 must be equal array2. I tryed to use the chai .eql() method but it didn't work.

like image 267
Brian Batista Avatar asked Oct 31 '17 17:10

Brian Batista


People also ask

Can we compare two arrays directly?

Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).

How do I compare two arrays of objects in Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.


1 Answers

The following solution:

  • will verify that the arrays have an equal number of elements
  • does not impose restrictions on keys (as to not contain a certain delimiter)
  • requires both keys and (string) values to be the same
  • has a time complexity of O(nlogn) (instead of O(n²) as some other solutions here)

function equalArrays(a, b) {
    if (a.length !== b.length) return false;
    const ser = o => JSON.stringify(Object.keys(o).sort().map( k => [k, o[k]] ));
    a = new Set(a.map(ser));
    return b.every( o => a.has(ser(o)) );
}

// Example
var array1 = [{"key1":"Banana", "key2":"Yammy"}, {"key1":"Broccoli", "key2":"Ew"}];
var array2 = [{"key1":"Broccoli", "key2":"Ew"}, {"key1":"Banana", "key2":"Yammy"}];
console.log(equalArrays(array1, array2)); // true
// Example with different key name
var array1 = [{"key0":"Banana", "key2":"Yammy"}, {"key1":"Broccoli", "key2":"Ew"}];
var array2 = [{"key1":"Broccoli", "key2":"Ew"}, {"key1":"Banana", "key2":"Yammy"}];
console.log(equalArrays(array1, array2)); // false
like image 192
trincot Avatar answered Sep 30 '22 09:09

trincot