Alex Rivera | Logout

Get size of dimensions in array

Asked 2012-04-19T22:16:28.183
32

How to get the dimensions given a multidimensional array?
Edit: it could be of 1, 2, or 3 dimensions but each sub-array has the same length.

i.e. for

var a = [[1,1,1], [1,1,1]]

would be [2,3]

Edit
Report

2 Answers

10

Considering that sub lists can have different size, get the minimum size or depending on need make it max

function size(ar){
    var row_count = ar.length;
    var row_sizes = []
    for(var i=0;i<row_count;i++){
        row_sizes.push(ar[i].length)
    }
    return [row_count, Math.min.apply(null, row_sizes)]
}
size([[1, 1, 1], [1, 1, 1]])

Output:

[2, 3]
answered 2012-04-19T22:26:39.917
2
var dim = [
    a.length,
    a[0].length
];

This should work, given that each sub array is the same length, however, if thats not the case, you might want to do something like:

function findDim(a){
    var mainLen = 0;
    var subLen = 0;

    mainLen = a.length;

    for(var i=0; i < mainLen; i++){
        var len = a[i].length;
        subLen = (len > subLen ? len : subLen);
    }

    return [mainLen, subLen];
};
answered 2012-04-19T22:19:43.540

Your Answer