Get size sizes in an array

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

i.e. for

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

will be [2,3]

+7
source share
5 answers
 var dimensions = [ arr.length, arr[0].length ]; 

This works because the length of the internal arrays never changes.

+10
source

Given that auxiliary lists can have different sizes, get the minimum size or, depending on the 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] 
+6
source
 var dim = [ a.length, a[0].length ]; 

This should work, considering that each additional array has the same length, however, if that is not the case, you can 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]; }; 
+1
source

This works for any dimension (assuming each additional array has the same length):

 function getDim(a) { var dim = []; for (;;) { dim.push(a.length); if (Array.isArray(a[0])) { a = a[0]; } else { break; } } return dim; } 
+1
source
 var a = [[1,1,1], [1,1,1]]; var size=[]; while(s=a.pop) size.push(s.length); 

Or if you want to have a length inside a :

 var a = [[1,1,1], [1,1,1]]; for(i in a) a[i]=a[i].length; 

Edit: Sorry, I was not in the subject. The following code calculates the maximum row and column for a two-dimensional array.

 var innerSize = 0, i=0, l=a.length, l2; for(;i<l;i++) if(innerSize<(l2=a[i].length)) innerSize = l2 [l, innerSize] 

You can change < to > if you want a minimum size.

0
source

All Articles