arr1 = [
{Lattitude: '52,4043000', Location: 'a2', Longitude: '55,7181815'},
{Lattitude: '52,3882320', Location: 'b2', Longitude: '55,7225500'},
{Lattitude: '52,4041184', Location: 'c2', Longitude: '55,7172296'},
{Lattitude: '52,3996194', Location: 'd2', Longitude: '55,7200249'},
];
arr2 = [
{Lattitude: '52,3882320', Location: 'b2', Longitude: '55,7225500'},
{Lattitude: '52,4041184', Location: 'c2', Longitude: '55,7172296'},
{Lattitude: '52,3996194', Location: 'd2', Longitude: '55,7200249'}
];
how i can compare two json arrays arr1,arr2 an get just this element {Lattitude: '52,4043000', Location: 'a2', Longitude: '55,7181815'}
from arr1 which no in arr2
I`ll try to do like this
function objDiff(arr1, arr2) {
var resultArray = [];
for (var i = 0; i < arr1.length; i++) {
for (var j = 0; arr2.length; j++) {
if (parseFloat(parseFloat(arr1[i].Lattitude).toFixed(4)) != parseFloat(parseFloat(arr2[i].Lattitude).toFixed(4)) &&
parseFloat(parseFloat(arr1[i].Longitude).toFixed(4)) != parseFloat(parseFloat(arr2[i].Longitude).toFixed(4))) {
resultArray.push(arr1[i]);
}
}
}
return resultArray;
}
but my function not works, i don`t know why
解决方案
Try this,
function compareArr(arr1, arr2) {
var longArray = arr1.length >= arr2.length ? arr1 : arr2;
var shortArray = arr1.length < arr2.length ? arr1 : arr2;
return resultArr = longArray.filter(function (v) {
return shortArray.filter(function (iv) {
return v.Lattitude === iv.Lattitude
&& v.Location === iv.Location
&& v.Longitude === iv.Longitude;
}).length === 0;
});
}
var resultArr = compareArr(arr2, arr1);
Pass two array to this function in any sequense, the result will be same.