Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doing a "Diff" on an Associative Array in javascript / jQuery?

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!

like image 499
Matrym Avatar asked Apr 01 '10 07:04

Matrym


People also ask

Does JavaScript support associative array?

JavaScript does not support associative arrays. You should use objects when you want the element names to be strings (text). You should use arrays when you want the element names to be numbers.

Which function finds out difference between two arrays?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

What is the difference between a numeric and an associative array?

Numeric array − An array with a numeric index. Values are stored and accessed in linear fashion. Associative array − An array with strings as index. This stores element values in association with key values rather than in a strict linear index order.


1 Answers

Try this:

function diff(obj1, obj2) {
    var result = {};
    $.each(obj1, function (key, value) {
        if (!obj2.hasOwnProperty(key) || obj2[key] !== obj1[key]) {
            result[key] = value;
        }
    });

    return result;
}
like image 145
RaYell Avatar answered Sep 28 '22 06:09

RaYell