I have some working code, though it seems like it should be much more efficient. I feel there are too many filters working through the same data sets. Is there a cleaner or more efficient way of merging 2 arrays without duplicating?
const x = [1,3,7,4,9];
const y = [2,3,9,13,4];
const yFilteredByX = y.filter(element => x.includes(element));
const xFilteredByY = x.filter(element => y.includes(element));
const unique = (value, index, self) => {
return self.indexOf(value) === index;
};
const newArr = yFilteredByX.concat(xFilteredByY);
const uniqueArr = newArr.filter(unique);
console.log(uniqueArr);
Currently outputs [3,9,4] successfully.
I made a quick fiddle
Set for each arrayArray#filter and return only those in the second setconst _getCommonElements = (arr1 = [], arr2 = []) => {
const set1 = new Set(arr1), set2 = new Set(arr2);
return [...set1].filter(e => set2.has(e));
}
console.log( _getCommonElements([1,3,7,4,9], [2,3,9,13,4]) );
Create a Set from one, and then filter the other by checking if the set has elements.
const x = [1, 3, 7, 4, 9];
const y = [2, 3, 9, 13, 4];
const uniqueInX = new Set(x);
const uniqueInBoth = y.filter(e => uniqueInX.has(e));
console.log(uniqueInBoth);
It seems like you intend to calculate the intersection of two sets, thus the corresponding function operation from the mozilla developer docs can be used, e.g.
const x = [1, 3, 7, 4, 9];
const y = [2, 3, 9, 13, 4];
function intersection(setA, setB) {
let _intersection = new Set()
for (let elem of setB) {
if (setA.has(elem)) {
_intersection.add(elem)
}
}
return _intersection
}
const setX = new Set(x);
const setY = new Set(y);
const commonSet = intersection(setX, setY);
console.log(...commonSet); // [3, 9, 4]