2

Why does this code throw and out-of-bounds error, it seems like it should work fine.

var a = [[[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]]];
    var b = [3,4];
    console.log(jQuery.inArray(b,a[0][0]));
1
  • maybe because 'b' string doesn't exist in the a[0][0] array (is [3,4])? =) Commented Nov 18, 2012 at 17:13

2 Answers 2

3

You can't find it, because it's not there. In JavaScript, just because two arrays have similar contents doesn't mean that the arrays themselves are equal. Try the following in your console:

[3,4] === [3,4];

The output will be that of false, since two similar arrays are not the same array. If you wanted this code to work, you'd have to actually put one array into another, like this:

var a = [3,4];
var b = [5,a]; // [5,[3,4]]

jQuery.inArray(a, b); // a is found at index 1

If you merely want to check for the presence of a similar array within the haystack, you could stringify the entire needle and haystack, and look for the substring:

var needle = JSON.stringify([3,4]);
var haystack = JSON.stringify([[3,4],[5,6]]);

haystack.indexOf(needle); // needle string found at index 1

You should note however that the index returned is the index the stringified representation is found at, and not the actual index the array is found at within the haystack. If you wanted to find the true index of the array, we'd have to modify this logic just a bit:

var needle = JSON.stringify([3,4]),
    haystack = [[3,4],[5,6]],
    position = -1,
    i;

for (i = 0; i < haystack.length; i++) {
    if (needle === JSON.stringify(haystack[i])) {
        position = i;
    }
}

console.log(position); // needle found at index 0​​​

Run this code: http://jsfiddle.net/DTf5Y/

Sign up to request clarification or add additional context in comments.

5 Comments

But I need to find array a in array b, what would be another way to do it?
But a array values can be any arrays, so I need found direct this array [3,4]
@user1833872 I understand. Stringify both arrays, and look up one in the result of the other.
var a = [[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]]; var b = [3,4]; var a_string = JSON.stringify(a); var b_string = JSON.stringify(b); console.log(b_string.indexOf( a_string )); returns -1
You should be trying to find b within a in that example.
0

The problem is that you have too many square braces.

var a = [[[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]]];
    var b = [3,4];
    console.log(jQuery.inArray('b',a[0][0]));

should be

var a = [[3,4],[0,0],[0,6],[7,8],[0,9],[8,3]];
    var b = [3,4];
    console.log(jQuery.inArray('b',a[0][0]));

Comments

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.