Nate - 11 months ago 56

Javascript Question

I'm learning to code on freecodecamp at the moment and I'm tasked to complete a task. Here it is.

Create a function that takes two or more arrays and returns an array of the symmetric difference (△ or ⊕) of the provided arrays.

Given two sets (for example set A = {1, 2, 3} and set B = {2, 3, 4}),

the mathematical term "symmetric difference" of two sets is the set of

elements which are in either of the two sets, but not in both (A △ B =

C = {1, 4}). For every additional symmetric difference you take (say

on a set D = {2, 3}), you should get the set with elements which are

in either of the two the sets but not both (C △ D = {1, 4} △ {2, 3} =

{1, 2, 3, 4}).

What I have tried is to concat all the elements of the arguments object. I'm trying to use the native filter method to filter out elements in the array which have occured more than once. Here is what I have tried at the moment.

`function sym() {`

let args = Array.prototype.slice.call(arguments);

return args.reduce((prev,current) => prev.concat(current),[]) //concat all arguments

.filter((element, index, array) => array.indexOf(element) !== index);

}

Can someone take a look and help me out? It would be much appreciated!

Answer Source

You could filter first `a`

and then `b`

and concat the result.

```
function symetricalDifference(a, b) {
function isNotInSet(set){
return function (value) {
return set.indexOf(value) === -1;
}
}
return a.filter(isNotInSet(b)).concat(b.filter(isNotInSet(a)));
}
console.log(symetricalDifference([1, 2, 3], [2, 3, 4])); // [1, 4]
console.log(symetricalDifference([1, 4], [2, 3])); // [1, 4, 2, 3]
```