MrGuru
MrGuru

Reputation: 345

If item is in any dimension of multi-dimensional array

I have an array that, for example, is 2d and looks like this: `var arr = [["1", "2", "3"], ["4", "5"], ["6"]];'

When I run $.inArray("4", arr); or arr.indexOf("4"), I get -1 meaning it is not in the array. However, it is in one of the inner arrays.

How can I tell if it is in the array or in any arrays that are elements in the array? In other words in any dimension of the array.

Upvotes: 0

Views: 65

Answers (2)

Amit Joki
Amit Joki

Reputation: 59252

You can do:

var arr = [["1", "2", "3"], ["4", "5"], ["6"]];
if(arr.join().split(',').indexOf("4") != -1){
   // do something.     
}

.join() converts the array to comma separated elements and .split(',') creates a new array out of it, which is a flattened one. So, .indexOf() works now.

Upvotes: 1

Jon
Jon

Reputation: 437386

The better engineered solution would be to create a recursive function that searches an array for a value.

If the array is only two levels deep as in the example there is also a more convenient solution: flatten the array and simply use indexOf:

var arr = [["1", "2", "3"], ["4", "5"], ["6"]];
var flattened = Array.prototype.concat.apply([], arr);
alert(flattened.indexOf("4"));

Upvotes: 2

Related Questions