Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array is multidimensional? (jQuery)

I have two arrays of AJAX (JSON) response:

One dimension:

[["fili","Chif"],["Bart","deme"],["Bomb","Jyui"],["Joiu","FDPi"],["Doen","abcd"],["drog","MAIC"],["Jasi"
,"abcd"],["Jere","Jibi"]]

Three dimensions:

[[["5","#"],["2","N"],["L","7"],["C","8"],["F","W"],["K","T"],["Q","E"],["Z","\/"]],[["B","O"],["$","P"
],["1","Y"],["H","R"],["3","%"],["I","U"],["M","4"],["A","9"]],[["J","X"],["Bye","G"],["D","V"],["Bye"
,"6"]]]

I try to check if an array is multidimensional but does not work:

if (typeof arr[0][0] != "undefined" && arr[0][0].constructor == Array) {
     return true;
} 
like image 768
FBN Avatar asked Jun 28 '15 21:06

FBN


People also ask

How do you check if an array is in a 2D array?

Look for array. shape: if it comes like (2,) means digit at first place but nothing after after comma,its 1D. Else if it comes like (2,10) means two digits with comma,its 2D.

How do you check if a 2D array contains a value JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found.

How to access multidimensional array in JS?

To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.

How to declare a multi dimensional array in JavaScript?

Here is how you can create multidimensional arrays in JavaScript. let student1 = ['Jack', 24]; let student2 = ['Sara', 23]; let student3 = ['Peter', 24]; // multidimensional array let studentsData = [student1, student2, student3];


2 Answers

You need to check the first element of Array so use

if(arr[0].constructor === Array)

DEMO

alert("[[]] returns " + ([[]].constructor === Array))
like image 117
bugwheels94 Avatar answered Oct 25 '22 09:10

bugwheels94


You can also check all elements in the array so I think it would be more right way in 2019

const is2dArray = array =>  array.every(item => Array.isArray(item));
like image 30
Stanislav Padimanskas Avatar answered Oct 25 '22 07:10

Stanislav Padimanskas