FBN
FBN

Reputation: 185

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;
} 

Upvotes: 10

Views: 20208

Answers (5)

Tim
Tim

Reputation: 3188

Instead of using the constructor property, you may also use instanceof:

var arr = [];
var obj = {};

(arr instanceof Object)
// -> true

(obj instanceof Object)
// -> true

(arr instanceof Array)
// -> true

(obj instanceof Array)
// -> false

Upvotes: 0

Stanislav Padimanskas
Stanislav Padimanskas

Reputation: 111

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));

Upvotes: 11

Shibhe Tepa
Shibhe Tepa

Reputation: 100

if(array[0][0] === undefined){
    return true;
}else{
    return false;
}

this one checks if the Array is a multi or just a normal array.

Upvotes: -1

JohnP2
JohnP2

Reputation: 2167

If you like my answer, please vote for the person above me, but here is the above answer reconstructed in function format:

function is2dArray(array){
    if(array[0] === undefined){
        return false;
    }else{
        return (array[0].constructor === Array);
    }
}

demo

Upvotes: 4

bugwheels94
bugwheels94

Reputation: 31920

You need to check the first element of Array so use

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

DEMO

alert("[[]] returns " + ([[]].constructor === Array))

Upvotes: 22

Related Questions