You can do that in following steps:
- First get those elements of
a which are not in b - Then get those elements of
b which are not in a - Then
concat() both the arrays.
let a = ["ABC", "DEF"] let b = ["ABC", "DEF", "GHI"] const res = a.filter(x => !b.includes(x)).concat(b.filter(x=> !a.includes(x))) console.log(res)
How the code works
Consider the line
a.filter(x => !b.includes(x))
filter() is array method which takes a callback. If callback returns true then the element will be added to result array otherwise not.
So now in above code x is element of array b through which we are iterating. b.includes(x) will return true if x is present in array b otherwise false.
! operator converts true to false and vice verse
So if x will be inside b it will return true. So by ! it will be become false and false will be returned from callback. So the element x will not be included in result/filtered array.
The sentence for the line above line is that "It get only those items of array a which are not present in b"
The second line
b.filter(x=> !a.includes(x))
Gets those elements of b which are not in a.
Atlast concat() is used to join both array.
balways contain every element ofa?a=['ABC','ABC']andb = ['DEF']what will be result?