javascriptarraysjsonchaiunordered

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.


Solution

  • You can array#join each value of the object on an separator and then generate a new array of string and then compare each values using array#every and array#includes

    var array1 = [{"key1":"Banana", "key2":"Yammy"}, {"key1":"Broccoli", "key2":"Ew"}];
        array2 = [{"key1":"Broccoli", "key2":"Ew"}, {"key1":"Banana", "key2":"Yammy"}];
        values = (o) => Object.keys(o).sort().map(k => o[k]).join('|'),
        mapped1 = array1.map(o => values(o)),
        mapped2 = array2.map(o => values(o));
    
    var res = mapped1.every(v => mapped2.includes(v));
    
    console.log(res);