Compare two arrays and filter out different elements (with arrays to remove duplicates)

Chatting in the group, I talked about this question, and some big guys answered it, hereby record the learning;
Let's talk about the problem first:


There are two ways: one is to use ES6 writing, which is very tall:
    
let a=[1,2,3,4], b=[1,2,3,5,4,6],
c = [...a, ...b],
d = new Set(c),
e = Array.from(d),
f = [...e.filter(_=>!a.includes(_)),...e.filter(_=>!b.includes(_))];
console.log(f);//[5, 6]
I know that ES6 has become popular, but for me, it is only after some information that I can understand, Dish!
First of all, the "...", the three dots or the ellipsis is a new method added by ES to the array, the scientific name is called the spread operator, and its main functions are complex array , merge arrays, Combined with destructuring assignment, string to array, An object that implements the Iterator interface, Map and Set structure, Generator function ( click to view teacher Ruan Yifeng's explanation ),
What is used here is the merging of arrays, merging them into an array.
Then, the role of d is converted into a set, which is a data structure provided by ES6. It is mainly used here because it does not contain repeated elements, so it is converted into a data structure without repeated elements (I dare not say that collections and arrays), array deduplication so easy!
Then, the role of the e variable is simple and clear. Convert the array-like data structure of d into an array, and the array contains the union of the two arrays.
Then, there are more things in the f variable, the first is the includes method. You should know the meaning of inclusion by looking at the name. This means that a contains this element and returns true, otherwise it returns false. After receiving the inversion of the result of the includes function, the filter method of the array filters out the elements that do not contain a in e, and then Add the elements that do not contain b in e, and reconstitute an array, which is the final result;
I tried to explain it in the way of Venn diagram (that is, the intersection, union, and negation), but the math is too bad, there is no way, whoever of you is good at math can send it to me privately. . .

The second method: (ground gas, good compatibility, support IE8)
function diff(arr1,arr2){
var a = [];
var b = [];

for(var i=0;i<arr2.length;i++){
    a[arr2[i]]=true;
}

for(var i=0;i<arr1.length;i++){
    if(!a[arr1[i]]){
        b.push(arr1[i]);
    }
}
console.log(b)
}
let aa = ["a","b"],bb=["a"];
diff(aa,bb);//"b"
This method is clear at first glance, it is simple to move, and it is also a relatively stable method. If you don't know it, just Google it yourself. .

Contact me: [email protected]




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324809338&siteId=291194637