Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

javascript - How to take element from two json arrays in jquery

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...