I have been writing the code to make a symmetric difference between to or more arrays. As you know, the symmetric difference is about excluding the elements which are in both sets of datas. More info: https://en.wikipedia.org/wiki/Symmetric_difference
This is my code:
//This function drops any repeated element 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 concat 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 don't understand what am I doing wrong. I expected to get a result of [3,4,5]
but that is not the result I get.