2
[1,2,3].CONTAINS([1,2]) ==> true
[1,2,3].CONTAINS([1,2,3,4]) ==> false

or

{a:1,b:2,c:3}.HASKEYS([a,b]) ==> true
{a:1,b:2,c:3}.HASKEYS([a,b,c,d]) ==> false

Is there a single function to check an array contains another array?

1
  • 1
    +1 as there's nothing wrong with the question. I don't believe there is a ready one, you'll be better off writing your own. Commented Apr 24, 2013 at 5:25

1 Answer 1

4

No, but you can make one:

Array.prototype.contains = function(other) {
    for (var i = 0; i < other.length; i++) {
        if (this.indexOf(other[i]) === -1) return false;
    }

    return true;
}

And if order matters:

Array.prototype.contains = function(other) {
    var broken;

    if (!other.length) return true;

    for (var i = 0; i < this.length - other.length + 1; i++) {
        broken = false;

        for (var j = 0; j < other.length; j++) {
            if (this[i + j] !== other[j]) {
                broken = true;
                break;
            }
        }

        if (!broken) return true;
    }

    return false;
}

The other function is similar, so I'll leave it to you to finish:

Object.prototype.has_keys = function(keys) {
    ...
}
Sign up to request clarification or add additional context in comments.

3 Comments

The question is likely not detailed enough, but from it, I was expecting "[1,2,3].contains([2,1])" should return false. Your implementation makes it return true.
nicely done @Blender, I think another loop is needed in there to detect all occurrences of other[0]. Otherwise the following returns false: "[1,2,3,2,1].contains([2,1])"
@TimothéeGroleau: Yep, thanks. I have a feeling that there may be a nicer way of writing it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.