Filtering a subset of an array - Stack Overflow
某草草
某草草 2017-05-19 10:42:41
0
4
685

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?

某草草
某草草

reply all(4)
某草草

https://lodash.com/docs/4.17....

巴扎黑
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;
  })
}
小葫芦

Use native solution

Using Array’s filter method can solve your problem. The specific implementation is very simple, and others have also answered it.

Solution with the help of third-party libraries

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]
迷茫

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];
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template