Pavel Valeriu Pavel Valeriu - 1 year ago 81
Javascript Question

How to find differences between two JavaScript arrays of objects?

I have two JavaScript arrays

(the original array of objects) and
(the updated orig array of objects) that have the same length and contain objects, and I want to output the differences between the each pair of objects.


var orig = [{enabled:"true", name:"Obj1", id:3},{enabled:"true", name:"Obj2", id:4}];

var update = [{enabled:"true", name:"Obj1", id:3}, {enabled:"true", name:"Obj2-updated", id:4}];

The output should be:

I implemented something but it needs optimization...

for(var prop=0; prop<orig.length; prop++) {
for(prop=0; prop<update.length; prop++) {
if(orig[prop].enabled != update.enabled) { console.log(update.enabled) }
if(orig[prop].name != update[prop].name) { console.log(update[prop].name) }
if(orig[prop].id != update[prop].id) { console.log(update[prop].id) }

Answer Source

You could filter the keys and get a result set with the updated keys.

var orig = [{ enabled: "true", name: "Obj1", id: 3 }, { enabled: "true", name: "Obj2", id: 4 }],
    update = [{ enabled: "true", name: "Obj1", id: 3 }, { enabled: "true", name: "Obj2-updated", id: 4 }],
    difference = [];

orig.forEach(function (a, i) {
    Object.keys(a).forEach(function (k) {
        if (a[k] !== update[i][k]) {
            difference.push({ id: update[i].id, key: k, value: update[i][k], index: i });


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download