Skip to content Skip to sidebar Skip to footer

How To Compare Two Javascript Array Using Angular.foreach

I have two javascript Object var obj1= { key1:'value1', key2:'value2' }; And var obj2= { key1:'value1', key2:'someOtherValue'

Solution 1:

Please dont use angular.foreach.

  • Javascript for is faster.
  • you wont be able to use break in angular.foreach.

var diffs = [];
for (var key in obj1) {
   if obj1[key] !== obj2[key]{
     diffs.append([key]);
   }
}
console.log(diffs)

Assuming both dictionaries have same keys..

Solution 2:

In plain Javascript, you could use a Map for it.

var obj1 = { key1: 'value1', key2: 'value2' },
    obj2 = { key1: 'value1', key2: 'someOtherValue' },
    map = newMap();

Object.keys(obj1).forEach(k => map.set(k, obj1[k]));
Object.keys(obj2).forEach(k => map.get(k) !== obj2[k] && console.log(k + ' is different'));

Solution 3:

Here is pure angularjs code with angular foreach loop.

var keepGoing = true;
angular.forEach(obj1, function(value, key){
    angular.forEach(obj2, function(value2, key2){
        if(keepGoing) {
            if(value == value2){
                keepGoing = true;
            }
            else{
                console.log('Difference is at', key2)
                keepGoing = false;
            }
        }
    })
})

Post a Comment for "How To Compare Two Javascript Array Using Angular.foreach"