简体   繁体   中英

How to compare Between two arrays and check if all items in one are in the second?

I have two arrays with values

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

if all items from b are in a so i want to return true

another example

a = [123,55,12,66]
b = [123,551]

will return false because 551 is not in a

i tried to go over all items in b and return false if i get an item that isn't in a.

Use .every() with .indexOf() .

b.every(function(n) {
    return a.indexOf(n) > -1;
});

You can also create a reusable function, and set the second argument to the array to search.

function itemIsInThis(n) {
    return this.indexOf(n) > -1;
}

And use it like this:

b.every(itemIsInThis, a);

The second argument to .every() (and most other Array iteration methods) will set the this value of the callback, so here we just set this to the a array.

A simple loop is all you need

function allIn(needles, haystack) {
    var i = needles.length;
    while (i--) // loop over all items
        if (haystack.indexOf(needles[i]) === -1) // normal existence check
            return false; // failed test
    return true; // none failed test
}

var a, b;
a = [1,2,3,4,5];
b = [1,3,5];
allIn(b, a); // true

a = [123,55,12,66];
b = [123,551];
allIn(b, a); // false

You can intersect the arrays and compare the result:

Array.prototype.intersect = function (arr1) {

    var r = [], o = {}, l = this.length, i, v;
    for (i = 0; i < l; i++) {
        o[this[i]] = true;
    }
    l = arr1.length;
    for (i = 0; i < l; i++) {
        v = arr1[i];
        if (v in o) {
            r.push(v);
        }
    }
    return r;
};

Array.prototype.containsAll = function (arr) { 
    return arr.intersect(this).length === arr.length;
};

var a = [123,55,12,66],
    b = [123,551],
    c = [1,2,3,4,5],
    d = [1,3,5];

console.log(c.containsAll(d), a.containsAll(b));

http://jsfiddle.net/bgK5q/

You can use $.grep and $.inArray to be more jQuery'ish

$.grep(b, function(el) {return $.inArray(el, a)!=-1});

and to return a boolean compare the length

b.length == $.grep(b, function(el) {return $.inArray(el, a)!=-1}).length;

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM