krish krish - 3 years ago 94
jQuery Question

Compare 2 arrays and remove duplicates

I am trying to compare 2 arrays using jquery and remove duplicates from that.

This is my code.Is this logic correct?

var list1 = [6, 7, 3, 4, 1, 2];
var list2 = [2, 4, 6, 5, 1, 9, 8, 7, 8];

var newArray = [];
var index1, index2;
$.each(list1, function(i, value)) {
index1 = $.inArray(list1[i]);
index2 = $.inArray(newArray[i]);
if (index2 == -1) {
newArray.push(list2[i]);
}
}


Expected output:

[3,5,9,8]


I should use only
$.each
,
$.inArray
and
.push
.

Answer Source

Try like this

<script type="text/javascript">
    var arr1=[6,7,3,4,1,2];
    var arr2=[2,4,6,5,1,9,8,7,8];
    $(document).ready(function(){
        var newArray=$.merge($(arr1).not(arr2).get(),$(arr2).not(arr1).get());
        console.log(newArray);
    });
</script>

It give out put as

[ 3, 5, 9, 8,8 ]

Another answer with using $.each,$.inArray and .push only Try this

var list1 = [6, 7, 3, 4, 1, 2];
var list2 = [2, 4, 6, 5, 1, 9, 8, 7, 8];

var newArray = [];
$.each(list1, function(i, value){
    if($.inArray(value,list2)==-1){
        newArray.push(value);
    }
});
$.each(list2, function(i, value){
    if($.inArray(value,list1)==-1){
        newArray.push(value);
    }
});
newArray=$.unique(newArray);
console.log(newArray);

It give out put as

[ 3, 5, 9, 8]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download