I am trying to figure out a solution for symmetric difference using javascript that accomplishes the following objectives:
- accepts an unspecified number of arrays as arguments
- preserves the original order of the numbers in the arrays
- does not remove duplicates of numbers in single arrays
- removes duplicates occurring across arrays
Thus, for example, if the input is ([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]), the solution would be, [1, 1, 6, 5, 4].
I am trying to solve this as challenge given by an online coding community. The exact instructions of the challenge state,
Create a function that takes two or more arrays and returns an array of the symmetric difference of the provided arrays.
The mathematical term symmetric difference refers to the elements in two sets that are in either the first or second set, but not in both.
Although my solution below finds the numbers that are unique to each array, it eliminates all numbers occuring more than once and does not keep the order of the numbers.
My question is very close to the one asked at finding symmetric difference/unique elements in multiple arrays in javascript. However, the solution does not preserve the original order of the numbers and does not preserve duplicates of unique numbers occurring in single arrays.
function sym(args){
var arr = [];
var result = [];
var units;
var index = {};
for(var i in arguments){
units = arguments[i];
for(var j = 0; j < units.length; j++){
arr.push(units[j]);
}
}
arr.forEach(function(a){
if(!index[a]){
index[a] = 0;
}
index[a]++;
});
for(var l in index){
if(index[l] === 1){
result.push(+l);
}
}
return result;
}
symsym([1, 1, 2, 6], [2, 3, 5], [2, 3, 4]); // => Desired answer: [1, 1, 6. 5. 4]
Create a Map with a count of all unique values (across arrays). Than concat all arrays, and filter non unique values using the Map.
Alternative: Use the lookup inside a map instead of an array
And it would return the output as: [3,5,4]
I came across this question in my research of the same coding challenge on FCC. I was able to solve it using
for
andwhile
loops, but had some trouble solving using the recommendedArray.reduce()
. After learning a ton about.reduce
and other array methods, I thought I'd share my solutions as well.This is the first way I solved it, without using
.reduce
.After learning and trying various method combinations, I came up with this that I think is pretty succinct and readable.
That last
.filter
line I thought was pretty cool to dedup an array. I found it here, but modified it to use the 3rd callback parameter instead of the named array due to the method chaining.This challenge was a lot of fun!
Another simple, yet readable solution:
Used functions: Array.prototype.filter() | Array.prototype.reduce() | Array.prototype.includes()