oggmonster
oggmonster

Reputation: 4872

Array contains all elements in other array

Been trying to figure out how to do this for a while, but haven't had any success yet. If I have 2 arrays like this:

array1 = [
    { name: 'John', age : 25},
    { name: 'Jane', age : 58}
]
array2 = [
    { name: 'Jane', age : 58},
    { name: 'John', age : 25}
]

How can I chech if array1 contains all the elements of array2? Note - the ordering doesn't matter, I want to be able to write something like this:

if array1.containsAll array2
    console.log 'array1 contains all of the elements in array2'
else
    console.log 'array1 does not contain all of the elements in array2'

I've tried using the contains function, but I get an error like this:

Object .... has no method 'contains'

Upvotes: 0

Views: 180

Answers (1)

Billy Moon
Billy Moon

Reputation: 58601

I doubt this method has good performance, but it should be pretty robust, and is super simple to understand...

# sort function to marshall data into consistent format
sortfunc = (a,b)-> JSON.stringify(a) < JSON.stringify(b)

# if serialized, sorted arrays are equal, then all items are present
if JSON.stringify(array1.sort(sortfunc)) == JSON.stringify(array2.sort(sortfunc))
    console.log "same"
else
    console.log "different"

n.b. caveat is that order of object keys may or may not be significant, depending on whether JS engine respects object index order (JS spec states it is not required)

Upvotes: 1

Related Questions