How would I test to see if a variable includes an multidimensional array? For example:
var obj = [1, 2];
vs
var obj = [[1], [2]];
I have used Array.isArray(obj) to test whether is an array, but I can't figure out how to test the number of arrays.
How would I test to see if a variable includes an multidimensional array? For example:
var obj = [1, 2];
vs
var obj = [[1], [2]];
I have used Array.isArray(obj) to test whether is an array, but I can't figure out how to test the number of arrays.
Share Improve this question edited May 23, 2014 at 18:33 user3180105 asked May 23, 2014 at 17:54 user3180105user3180105 3815 silver badges14 bronze badges 6- 2 That's easy, open the console and the second one will generate a syntax error ! – adeneo Commented May 23, 2014 at 17:55
-
if( Object.prototype.toString.call( someVar ) === '[object Array]' ) { alert( 'Array!' ); }
– tymeJV Commented May 23, 2014 at 17:57 - 3 A variable can always only contain a single value, hence it can only contain a single array. Maybe you used the wrong words to describe the problem. If so, please provide more context. – Felix Kling Commented May 23, 2014 at 17:59
- 1 Do u mean multidimensional arrays? – Comfortably Numb Commented May 23, 2014 at 18:00
-
1
Do you mean
var ratings = [[1], [2]]
? If so, you'd have to then check if each value is an array as well as checking ifratings
is an array. – forgivenson Commented May 23, 2014 at 18:01
1 Answer
Reset to default 7Assuming you meant
var ratings = [[1], [2]];
as var ratings = [1], [2];
is a syntax error, you could do
ratings.filter(Array.isArray).length
to get the number of arrays inside the wrapping array (2)
FIDDLE