0

I want to get difference in two array, I wrote this code. But it doesn't work with associative array.

code

function array_diff(older, newer){
    function callback_filter(element, index, array){
        return (this.indexOf(element) === -1);
    }

    return newer.filter(callback_filter, older);
}

result

array_diff([{a: "A"}, {b: "B"}], [{a: "A"}, {b: "B"}, {c: "C"}]);
>> [{a: "A"}, {b: "B"}, {c: "C"}]

Please advise.

hucuhy
  • 809
  • 3
  • 9
  • 15

1 Answers1

1

The problem is that your objects are not equal according to indexOf.

For example:

var a1 = {a: "A"};
var a2 = {a: "A"};

a1 == a2; // THIS IS FALSE

So you will need to implement your own test for equality. Does this have to work across any possible JS object?

You can convert your objects to strings and compare those, but this does not give good performance:

JSON.stringify(a1) === JSON.stringify(a2) // THIS IS TRUE

You may find this question helpful.

Community
  • 1
  • 1
Drew Noakes
  • 300,895
  • 165
  • 679
  • 742