var a = [1,2,3,4,5,6];
var b = [2,3,6];
Array b is a subset of array a, removed from a What are the optimal solutions for elements containing b?
巴扎黑2017-05-19 10:44:41
function diff(a1, a2) {
return a1.concat(a2).filter(function (val, index, arr) {
return arr.indexOf(val) === arr.lastIndexOf(val);
});
}
function diff2(a1, a2) {
return a1.filter(val => {
return a2.indexOf(val) === -1;
})
}
高洛峰2017-05-19 10:44:41
Using Array’s filter
method can solve your problem. The specific implementation is very simple, and others have also answered it.
If you don’t mind referencing third-party libraries, it is recommended that you introduce lodash. This library contains a large number of methods for processing arrays. If you have many array operation scenarios, it is highly recommended.
It has a function specifically to deal with this problem, called difference. Of course, a classmate said before that you can also use without, but it is not as convenient to use as difference.
The "_" in the code below is a default object after introducing lodash. All methods defined by lodash are under it, a bit like the "$" used after introducing jQuery
var a = [1,2,3,4,5,6];
var b = [2,3,6];
var result = _.difference(a, b); // result=[1,4,5]
迷茫2017-05-19 10:44:41
Why bother using the loadash
,直接用数组的filter
method:
var a = [1,2,3,4,5,6];
var b = [2,3,6];
var ans = a.filter((n) => !b.includes(n));
console.log(ans); //[1, 4, 5];