search

Home  >  Q&A  >  body text

Filtering a subset of an array - Stack Overflow

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?

某草草某草草2747 days ago688

reply all(4)I'll reply

  • 某草草

    某草草2017-05-19 10:44:41

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

    reply
    0
  • 巴扎黑

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

    reply
    0
  • 高洛峰

    高洛峰2017-05-19 10:44:41

    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]

    reply
    0
  • 迷茫

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

    reply
    0
  • Cancelreply