rex rex - 1 month ago 7
jQuery Question

Comparing two arrays and getting the non duplicate(not unique) values

I have two sets of arrays. I need to get the letters that are not in both arrays. First it should check if index 0 'a' is on both arrays. If it is in both than it should delete 'a' from both(just the first 'a' in first array not the one at the end(index 3). And go the the second item 'b' using same logic.

var arrayA = ['a','b','c','a'];

var arrayB = ['a','d','f','c'];

var arrayC = []; //Shoud have the result[b,a,d,f]

The code is set up at http://jsfiddle.net/rexonms/AbFYh/#base

HTML

<p class="arrayA">Array A</p>
<p class="arrayB">Array B</p>
<p class="arrayC">Array C</p>



jQuery

var arrayA = ['a','b','c','a'];
var arrayB = ['a','d','f','c'];
var arrayC = []; //Shoud have the result[b,a,d,f]

$('.arrayA').text('ArrayA: ' + arrayA);
$('.arrayB').text('ArrayB: ' + arrayB);

$.each(arrayA, function(indexA,valueA) {
$.each(arrayB, function(indexB, valueB){

if(valueA != valueB)
{
arrayC.splice(valueA);
}
});

$('.arrayC').text('ArrayC: ' + arrayC);
});

Answer

Here is a working version of what you want: http://jsfiddle.net/Zzt5f/

var arrayA = ['a','b','c','a'];
var arrayB = ['a','d','f','c'];
var arrayC = []; //Should have the result[b,a,d,f]

$('.arrayA').text('ArrayA: ' + arrayA);
$('.arrayB').text('ArrayB: ' + arrayB);

$.each(arrayA, function(indexA,valueA) {
    $.each(arrayB, function(indexB, valueB){
        if(valueA == valueB)
        {
            arrayA[indexA]=null;
            arrayB[indexB]=null;
            return false; //break out of inner each loop                     
        }
    });
});

$.each(arrayA.concat(arrayB),function(idx,val) {
    if(val!=null) arrayC.push(val);
});

$('.arrayC').text('ArrayC: ' + arrayC);
alert(arrayC);

As you see I made only a few modifications to your original code. Firstly, since you are trying to remove the duplicate values, you need to check if valueA==valueB, not vice-versa. Once a match has been found, the second iteration needs to halt to prevent removal of a second duplicate in the second array, hence the return false.

I didn't use the array.splice method, because this actually creates and returns a new array by removing values from the array it is called on, so essentially it wasn't doing anything the way you were using it. It felt cleaner to not keep creating new arrays within the loop. Note that this method will actually modify arrayA and arrayB, so if you need them again later on you will have to clone them.

Comments