开发者

How to get subset of two arrays in javascript?

What I am trying to do is if I have Array a = {1,2,3,4}; b = {1,2};

Then I want subset array as c = {3,4开发者_运维知识库};

Can anybody help me?


a = [1, 2, 3, 4]
b = [2, 1, 5]

comp = a.filter(function(e) { return b.indexOf(e) < 0 })

see Array.filter and Array.indexOf for more details and degradation options.


I'm not aware of any built-in way to do this, you basically have to loop through c and check whether each element is in a and, if so, remove it. The Array#indexOf method can help you with checking, but not all implementations have it (though most do). Removal can be via Array#splice.

So:

var a, c, index;
a = [1, 2];
c = [1, 2, 3, 4];
for (index = c.length - 1; index >= 0; --index) {
    if (a.indexOf(c[index]) >= 0) {
        c.splice(index, 1);
    }
}

...and then either supply your own implementation of Array#indexOf if your environment doesn't support it, or use a library like Prototype that supplies it for you (jQuery gives it to you as well, but through its own jQuery.inArray function). If doing it yourself:

if (!Array.prototype.indexOf) {
  (function() {
    Array.prototype.indexOf = Array_indexOf;
    function Array_indexOf(elm) {
      var index;
      for (index = 0; index < this.length; ++index) {
        if (this[index] === elm) {
          return index;
        }
      }
      return -1;
    }
  })();
}

Note that adding to the Array prototype as above can be dangerous when done with poorly-written code code that makes assumptions about the environment. Specifically, code that treats for..in as though it loops through array element indexes (it doesn't, it looks through object property names) will get messed up if you add to the Array prototype. (That's probably why jQuery doesn't do it.)

Live example


Assuming that you're after the relative complement of b in a.

function complement(a, b) {

  // convert A to an associative array
  var myHash = {};
  for (var i = 0; i < a.length; ++i) {
    myHash[a[i]] = 1;
  }

  // remove the elements that exist in B
  for (var i = 0; i < b.length; ++i) {
    delete myHash[b[i]];
  }

  // what's left is A \ B
  // assumes that no-one broke Array by adding new properties to the prototype
  return Object.keys(myHash);
}

// test
var a = [1, 2, 3, 4];
var b = [1, 2];
var c = complement(a, b);
alert(c);

This should scale well for larger arrays, since it uses hash table indexing rather than linear searches to remove the unwanted elements.


Here is another solution which uses Array.filter() and Array.includes()

function arrayDifference(a, b) {
  return a.filter((x) => !b.includes(x));
}

const a = [1, 2, 2, 2, 3, 4]
const b = [1, 2]

arrayDifference(a,b) // returns [3, 4]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜