0

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'
2
  • are you willing to consider a utility library, like underscore to get object comparison and composition? jsfiddle.net/no02qybh Commented Nov 12, 2014 at 3:13
  • There is no easy way to do this. alandarev's solution is close but you can't meaningfully compare the contents of objects using == (or ===) in JavaScript so you'd have to manually compare the values. You can hide some of the nastiness using a utility library (such as Underscore) but that's just shuffling the deck chairs around and hiding the complexity. Commented Nov 12, 2014 at 6:39

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

But there's no guarantee that { name: 'John', age : 25} will be '{"name":"John","age":25}' when JSONified rather than '{"age":25,"name":"John"}' and there's no guarantee that two JSON.stringify calls will put the keys in the same order. If you need the keys to be in a specific order (and you do), then you have to flatten them to arrays yourself.
Also, a sorting comparison function does not return a boolean value, it should return a positive, negative, or zero value to cover the three possibilities.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.