Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 arrays of objects with Underscore to find the differnce

I have 2 arrays, one is newVal and the other is origVal define

orig:

[
{"ListingId":1762276,"Rating":3,"ListPrice":7411828,"PropertyType":"Residential"},
{"ListingId":1826692,"Rating":3,"ListPrice":650000,"PropertyType":"Residential"},
{"ListingId":1833283,"Rating":4,"ListPrice":950000,"PropertyType":"Residential"},
{"ListingId":1832134,"Rating":3,"ListPrice":850000,"PropertyType":"Residential"},
{"ListingId":1829932,"Rating":4,"ListPrice":750000,"PropertyType":"Residential"},
{"ListingId":1827548,"Rating":5,"ListPrice":650000,"PropertyType":"Residential"}
]

new:

[
{"ListingId":1762276,"Rating":2,"ListPrice":7411828,"PropertyType":"Residential"},
{"ListingId":1826692,"Rating":3,"ListPrice":650000,"PropertyType":"Residential"},
{"ListingId":1833283,"Rating":4,"ListPrice":950000,"PropertyType":"Residential"},
{"ListingId":1832134,"Rating":3,"ListPrice":850000,"PropertyType":"Residential"},
{"ListingId":1829932,"Rating":4,"ListPrice":750000,"PropertyType":"Residential"},
{"ListingId":1827548,"Rating":5,"ListPrice":650000,"PropertyType":"Residential"}
]

If I change one of the ratings in new, how might I detect that change, and retrieve the changed object?

There will only be one change at a time, although I don't think that matters.

FYI: These arrays are being produced from an Anjularjs watchcollection

$scope.$watchCollection('items', function (new, old) {

}, true); 

Thank you, Stephen

like image 962
Stephen Patten Avatar asked Aug 22 '13 14:08

Stephen Patten


People also ask

How do I compare the contents of two arrays?

Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object. equals() .

How do I compare two arrays of arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

How do you compare two arrays to find matches?

JavaScript finding non-matching values in two arrays The code will look like this. const array1 = [1, 2, 3, 4, 5, 6]; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const output = array2. filter(function (obj) { return array1. indexOf(obj) === -1; }); console.


1 Answers

If the order does not change, a simple iteration will do it. Underscore provides the find method for this task:

var changedObj = _.find(newVal, function(obj, index) {
    return obj.Rating != oldVal[index].Rating;
});
like image 182
Bergi Avatar answered Sep 19 '22 03:09

Bergi