0

I have this array (below) and I'm trying to check if it has specific values.

var a = [ true, "lipsum" ];

What I need to do, is to check if a[0] is true and if a[1] is "lipsum"

I could check both values separately:

a[0] === true && a[1] === 'lipsum' // true

...to shorten the code a bit, I tried to do this:

a === [ true, 'lipsum'] // false

Why is this code example above false and is there another way to achieve what I'm trying to do?


I could do this:

a.join() === 'true,lipsum' // true

though I can't help but feel that there is a better way..?


2 Answers 2

1

For only two elements to check the straightforward way seems best, but I assume you want to do this for maintenance reasons because eventually you may have several conditions to check (not just two). If so, you can do something like the following, which seems verbose for only two conditions, but as you start adding more it would be more reasonable, so here's an example with 5 conditions to check:

// set a constant somewhere for your truth condition
var COND = [1, 'a', 5, 'b', 0];

// check `a` against the constant array using `every` (Thanks Bergi)
if (a.every(function(v, i){ return COND[i] === v; })) {
    // all array elements the same
}
Sign up to request clarification or add additional context in comments.

1 Comment

Use every() instead of filtering and comparing lengths
0

Each array is a separate object, so the equality operator cannot be used to compare them. Assuming that you have a strict comparison of known arguments to do, the first method you use is the best.

If you have another array of arguments that the original array must contain, you must use a loop, although you could abstract it:

Array.prototype.contains = function (array) {
    for (var x = 0; x < array.length; x++) {
        if (this.length < x || this[x] !== array[x]) {
            return false;
        }
    }
    return true;
}

http://jsfiddle.net/q5DvG/1/

7 Comments

I ran a jsperf to see how much .join would slow it down, which isn't that much... jsperf.com/array-vs-string123456789 ...but I figured that it isn't worth it and went with checking each one separately.
@Joonas .join will coerce elements to strings and your strict comparison will no longer make sense.
I don't see how it wouldn't make sense?
@Joonas [true].join() !== true
@Joonas I think there's a bit of a disconnect here .. comparing to static values known by you is small potatoes. You can write whatever you want. If you had to deal with variables, you could run into trouble if it was unclear what was coming in: true vs. "true"
|

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.