0

Is there any way to check if an array contains an array with specific values?

Like, I have this array

 drawn[0] = [0,0]

Which I later want to check if still contains [0,0], so I'd do something like

 drawn[0] == [0,0]

But this just returns a false, why? And, more importantly, what should I do instead? Even if I try [0,0] == [0,0] I get a false in return?

Please note that the arrays won't always just be zeros...

Ps. I don't want to use any external libraries, so please keep it to plain ol' javascript

Mobilpadde
  • 1,871
  • 3
  • 22
  • 29

4 Answers4

4

Everyone's said that you can't compare the arrays because they are objects. That is true. You have several viable solutions including nested loops (either blatantly or abstracted). Others have also suggested this.

A potentially simpler alternative is to compare the the toString values of the two arrays:

drawn[0].toString() == [0,0].toString()

This does require the array contents to be in the same order.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • Since you know what `[0,0]` will produce as a string, probably better to just compare to `0,0`. – RobG Feb 22 '13 at 05:55
  • @RobG I would assume that `[0,0]` is a variable in the context in which he's using it. It's also safer to use `toString()` anyway because you don't have to worry about the parsing of the value. For example, You may think `[0, 0].toString()` is `0, 0`, but it's not. It's `0,0`. – Explosion Pills Feb 22 '13 at 15:40
3

Arrays in JavaScript are only equal to one another if they're the same object.

You need to do a contents check instead:

if (drawn[0].every(function(item) { return item === 0; })) {
    // all entries are zero.
}

See also: Array.every()

Or in your specific case, simply:

if (drawn[0][0] === 0 && drawn[0][1] === 0) {
    // equal to [0, 0]
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
2

Check with a for loop, you can't compare with a simple comparison because it compares the references not the values:

[0]    !== [0]    // true
[0][0] ==  [0][0] //true
gdoron
  • 147,333
  • 58
  • 291
  • 367
0

Objects, including arrays, are compared by object identity. Each time you write [0, 0] you create a new array; so they register as different objects. You would need to iterate yourself through elements and inspect if the elements are the same.

Amadan
  • 191,408
  • 23
  • 240
  • 301