Diff //JavaScript Repository

Description

Compares two arrays and returns the distinct values.
Created: 2005.11.04

Code (Download)

//+ Carlos R. L. Rodrigues
//@ http://jsfromhell.com/array/diff [rev. #1]

diff = function(v, c, m){
    var d = [], e = -1, h, i, j, k;
    for(i = c.length, k = v.length; i--;){
        for(j = k; j && (h = c[i] !== v[--j]););
        h && (d[++e] = m ? i : c[i]);
    }
    return d;
};

Example (Example)

<script type="text/javascript">
//<![CDATA[

var a = [1,2,4,5,7], b = [1,2,3,9];

document.write(
    "A = ", a, "<br />B = ", b, "<br /><br />",
    "diff(A, B) = ", diff(a, b), "<br />",
    "diff(B, A) = ", diff(b, a)
);

//]]>
</script>

Help

diff(vector: Array, comparator: Array, [useIndex: Boolean = false]): Array
Compares the array with another (comparator) and, returna an array with the values from comparator that doesn't exists on vector.
vector
array that will be checked
comparator
array that will be compared
useIndex
if true, it will be returned an array containing just the index of the comparator's elements, otherwise returns the values

Rank (Votes: 24)

3.21