1

Is there a more elegant way in CoffeeScript to compare elements within arrays?

For "is any of these elements in the array" I do:

if "b0" in myArr or "b1" in myArr or "b1" in myArr

And for "are all of these elements in the array" I do:

if "b0" in myArr and "b1" in myArr and "b1" in myArr

Thank you very much for your help on this beginner question.

1 Answer 1

1

For "is any of these elements in the array" I do:
if "b0" in myArr or "b1" in myArr or "b1" in myArr

It is convenient to use Array methods for this. Array.prototype.some is useful:

['b0', 'b1', 'b2'].some(function(el) {
    return myArr.indexOf(el) > -1;
});

And for "are all of these elements in the array" I do:
if "b0" in myArr and "b1" in myArr and "b1" in myArr

And here you can use Array.prototype.every:

['b0', 'b1', 'b2'].every(function(el) {
    return myArr.indexOf(el) > -1;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you dfsq for that little trick. I was sure CoffeeScript had something convenient "build in", but couldn't find proper examples anymore.
I'm not coffescript guy, but I don't think it has something that specific. After all, it's just normal JS. You just need to translate it to CS syntax.

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.