Compare order-independent arrays of objects

I have 2 arrays of objects and I have to compare them, but the order of the objects does NOT matter . I cannot sort them because I will not have the names of their keys, because the functions must be shared. The only information I will have about the array is that both objects in the array have the same number of keys, and these keys have the same name. Thus, array1 must contain the same objects as array2.

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

In this example, array1 should be equal to array2. I tried using the chai method .eql(), but that did not work.

+4
source share
3 answers

array#join , , array#every 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);
Hide result
+2

, , , , , () , O (nlogn) O (n²):

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
Hide result
+1

- :

:

arr1.forEach( (obj) => {
    obj.representation = '';
    for (let key of Object.keys(obj)) {
      obj.representation += obj[key];
    }
}

arr2

, , .

:

arr1.sort( (a,b) => { return a.representation > b.representation } );
arr2.sort( (a,b) => { return a.representation > b.representation } );

let equal = arr1.every( (el, i) => arr2[i]===el );
0

Source: https://habr.com/ru/post/1688472/


All Articles