Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare unsorted arrays of objects in Javascript

I have to compare two unsorted arrays of objects, for example the following code should return true:

compareObjs(
    [{ foo: 'foo', bar: 'bar' }, { baz: 'baz' }], 
    [{ baz: 'baz' }, { foo: 'foo', bar: 'bar' }]
)

I know there are already plenty of answers about comparing arrays of objects, but I did not really find the clear one for comparing the unsorted version of arrays.

like image 257
Shota Avatar asked Sep 20 '25 17:09

Shota


1 Answers

Here another possibility:

const array2 = [1,3,2,4,5];

const isInArray1 = array1.every(item => array2.find(item2 => item===item2))
const isInArray2 = array2.every(item => array1.find(item2 => item===item2))

const isSameArray = array1.length === array2.length && isInArray1 && isInArray2

console.log(isSameArray); //true
like image 122
Jöcker Avatar answered Sep 22 '25 08:09

Jöcker