I think you really wanted to write:
<script type="text/javascript"> var a = ['a','b','c','d','e']; var b = ['a','d','e','c']; </script>
In any case, you can sort arrays and get values ββfrom values ββthat are not in another, and vice versa, then combine the two sets into one. You seem to be spoiled for choice, so here is a good basic version of JavaScript that should work in most browsers. Using the new features of the latest browsers will probably fail in older browsers.
// Compares a to b. Returns all the elements in a that are not in b // If c provided, add unique elements to c function getUnique(a, b, c) { var c = c || []; var ta = a.slice().sort(); var tb = b.slice().sort(); var x, y, found = false; for (var i=0, iLen=ta.length; i<iLen; i++) { x = ta.shift(); for (var j=0; j<tb.length && !found; j++) { // j.length changes each loop if (tb[j] == x) { tb.splice(j,1); // Remove match from b found = true; } } if (!found) { c.push(x); // If no match found, store in result } found = false; } return c; } var a = ['a','b','d']; var b = ['b','e']; var d = getUnique(a, b); alert(d); var c = getUnique(b,a,d); alert(d);
But your comment on the first answer indicates that you need elements that are common to both arrays, which is simpler:
function getCommon(a, b) { var c = []; var ta = a.slice().sort(); var tb = b.slice().sort(); var t, found; for (var i=0, iLen=ta.length; i<iLen; i++) { t = ta[i]; found = false; for (var j=0, jLen=tb.length; j<jLen && !found; j++) { if (t == tb[j]) { c.push(tb.splice(j,1)); found = true; } } } return c; } alert(getCommon(a, b));
You need to figure out what to do with duplicates. In the first case, duplicates will be considered as unique if there is no duplicate in another array. In the above example, duplicates do not matter if they are not duplicated in both arrays.