Joonas
Joonas

Reputation: 7303

Check array for multiple values in specific order

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..?


Upvotes: 0

Views: 102

Answers (2)

mVChr
mVChr

Reputation: 50185

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
}

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

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/

Upvotes: 0

Related Questions