If I have two associative arrays, what would be the most efficient way of doing a diff against their values?
For example, given:
array1 = {
foreground: 'red',
shape: 'circle',
background: 'yellow'
};
array2 = {
foreground: 'red',
shape: 'square',
angle: '90',
background: 'yellow'
};
How would I check one against the other, such that the items missing or additional are the resulting array. In this case, if I wanted to compare array1 within array2, it would return:
array3 = {shape: 'circle'}
Whilst if I compared array2 within array1, it would return:
array3 = {shape: 'square', angle: '90'}
Thanks in advance for your help!
A minha ficou assim:
This might be much more sophisticate than what you need, but you can try my jsondiffpatch lib that will diff any pair of javascript objects:
https://github.com/benjamine/jsondiffpatch
if you want to test it you can see it live in http://benjamine.github.com/jsondiffpatch/demo/index.html
RaYell's solution is nice but unfortunately will only tell you the items in obj2 that are either different from or non-existant in obj1, if we need to know both sides, let's get all keys and then compare. The following function will return an associative array with key values for each object. Oh... to be fair, I haven't tested yet, but this should work.
Oh, and while I do recognize that the first solution answered the initial question, I think the above solution offers another approach that the initial user might find useful so as to not require checking twice.
Try this:
If you're familiar with PHP syntax, take a look at http://phpjs.org/functions/index which includes almost all PHP's array related functions converted into JavaScript – including
array_diff