I have been attempting to create code that calculates the symmetric difference between two or more arrays. The symmetric difference involves excluding elements that are present in both datasets. For more information, check out this link: https://en.wikipedia.org/wiki/Symmetric_difference
Here is the code I have written:
//The unify function removes any duplicate elements from a vector
function unify(arr){
var result=arr.reduce(function(vector,num,index,self){
var len=self.filter(function (val){
return val===num;
}).length;
if (len>1){
var pos=self.indexOf(num);
self.splice(pos,1);
}
vector=self;
return vector;
},[]);
return result;
}
function sym(args) {
var arg = Array.prototype.slice.call(arguments);
var compact= arg.map(function(vector){
return unify(vector);
});
//We compare the vectors and delete any repeated element before we concatenate them
return compact.reduce(function(prev,next,index,self){
for (var key in next) {
var entry=next[key];
var pos=prev.indexOf(entry);
if (pos!==-1){
prev.splice(pos,1);
next.splice(key,1);
}
}
return prev.concat(next);
});
}
console.log(sym([1, 2, 3], [5, 2, 1, 4]));
I am puzzled as to why my code is not producing the expected result of [3,4,5]
. It seems there may be an issue with how the arrays are being compared and combined.