How to take element from two json arrays in jquery

半世苍凉 提交于 2019-12-13 09:49:27

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/33409643/how-to-take-element-from-two-json-arrays-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!