Get the unique values from two arrays and put them in another array
var array3 = array1.filter(function(obj) { return array2.indexOf(obj) == -1; });
MDN on Array#filter: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
Includes a polyfill for older browsers.
With a bit of ES6 magic it can be fairly concise. Note that we need to check both ways around in case there are unique items in either array.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [1, 3, 8];
let unique1 = arr1.filter((o) => arr2.indexOf(o) === -1);
let unique2 = arr2.filter((o) => arr1.indexOf(o) === -1);
const unique = unique1.concat(unique2);
console.log(unique);
// >> [2, 4, 5, 8]
var unique = [];
for(var i = 0; i < array1.length; i++){
var found = false;
for(var j = 0; j < array2.length; j++){ // j < is missed;
if(array1[i] == array2[j]){
found = true;
break;
}
}
if(found == false){
unique.push(array1[i]);
}
}
UPDATE The original post works but is not very fast, this implementation is a lot faster, this example uses only one array, but in the function you can easily pass any additional arrays to combine.
only a simple error check is done and more should be in place, use at own discretion, meant as working example only.
function Unique(array) {
var tmp = [];
var result = [];
if (array !== undefined /* any additional error checking */ ) {
for (var i = 0; i < array.length; i++) {
var val = array[i];
if (tmp[val] === undefined) {
tmp[val] = true;
result.push(val);
}
}
}
return result;
}
var unique = Unique([1, 2, 2, 6, 8, 5, 6, 8]);
Additionally this can be implemented as prototype of the Array object, changing the signature to
Array.prototype.Unique = function() {
var array = this;
...
}
and can be called like this:
var unique = [1, 2, 2, 6, 8, 5, 6, 8].Unique();