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.
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 }
// ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With