7

I want to compare two arrays using angular.equals and get list of items that are different from each other.

For example:

var obj1 = [
    { id: 1, name: 'john', age: 30, height: 6 },
    { id: 2, name: 'ben' , age: 20, height: 5 }
];
var obj2 = [
    { id: 1, name: 'martin', age: 25, height: 6 },
    { id: 2, name: 'ben'   , age: 20, height: 5 }
];

Now doing angular.equals(obj1, obj2) will return false.

Here I want to compare each item from different arrays and alert differences or show different color when I display in UI.

Assuming obj1 is from HTML form and obj2 is from service.

Result expected:

.id[1] name changed to john,age changed to 25
or
.get false or true when I compare each item in.

Phú
  • 48
  • 8
user2927423
  • 81
  • 1
  • 1
  • 2
  • 1
    There is no "out of the box" way of doing this in Angular. Ultimately, you just need to iterate through each array value and compare. Underscore/lodash may or may not help you beyond the Array.prototype methods available in JS. – Marc Kline May 29 '14 at 06:59
  • Can you please share in JSFiddle if you have solution , I am struggling in comparing and getting exact difference for each item. – user2927423 May 29 '14 at 07:09
  • I don't have a solution because I haven't worked through the problem. It would be best for you to post a Fiddle of what you have and update your question with more specifics about what you've tried. – Marc Kline May 29 '14 at 07:10
  • Marc Kline, I have updated the solution I tried here http://jsfiddle.net/Ebv3p/60/ – user2927423 May 29 '14 at 07:28
  • I updated it with just the very beginning of the diff you're looking for: http://jsfiddle.net/marcolepsy/Ebv3p/62/ I used Underscore, which I imagine you'll want to continue using. I suggest becoming acquainted with the methods it offers as you consider the problem you're looking to solve. – Marc Kline May 29 '14 at 08:06

2 Answers2

2

Angular doesn't have a built-in function for this. You should use the library deep-diff for this.

var first = [
    { id: 1, name: 'john', age: 30, height: 6 },
    { id: 2, name: 'ben' , age: 20, height: 5 }
];

var second = [
    { id: 1, name: 'martin', age: 25, height: 6 },
    { id: 2, name: 'ben'   , age: 20, height: 5 }
];

var result = diff(first, second);

// result => [
//    { kind: 'E', path: [0, 'name'], lhs: 'john', rhs: 'martin' },
//    { kind: 'E', path: [0, 'age' ], lhs: 30    , rhs: 25       }
// ]
Phú
  • 48
  • 8
-2

As klode stated here, there is an option to deep compare using angular only without additional dependencies:

angular.equals(obj1, obj2)
Community
  • 1
  • 1
Aviran Cohen
  • 5,581
  • 4
  • 48
  • 75