const dimensions = [ arr.length, arr[0].length ];

This works, if you know length of the inner arrays never change.


If the dimension of the inner arrays aren't static (jagged array), you could combine Array.reduce and Math.max to calculate the largest dimension:

const dimensions = [
    arr.length,
    arr.reduce((x, y) => Math.max(x, y.length), 0)
];
Answer from Alex on Stack Overflow
🌐
SitePoint
sitepoint.com › javascript
Multidimensional Array Length - JavaScript - SitePoint Forums | Web Development & Design Community
July 9, 2010 - Each element in a JavaScript array can itself be an array giving the equivalent of a multi-dimensional array but the lengths of the arrays iyou add for the second dimension are not forced to be the same and so while you have one length for the first dimentsion of the array each of those elements has its own separate length for the second dimension and so on for as many more arrays within arrays as you build.
🌐
Scaler
scaler.com › home › topics › what is a multidimensional array in javascript?
Multidimensional Array in JavaScript - Scaler Topics
July 14, 2024 - The only difference is that we have to use two or more indices to access the elements of the multidimensional array in javascript. There are some properties of Multi-Dimensional Array in JavaScript: length: The length function is used to return the size of the specified array.
Top answer
1 of 3
12

There's no shortcut, you have to sum up the lengths of the arrays. If you only have two dimensions, then:

var matrix = [1,2,3,4,5,6, [1,2,3,4]];
var sum = matrix.reduce(function(acc, entry) {
    return acc + (Array.isArray(entry) ? entry.length : 1);
}, 0);
console.log(sum);

If you may have more dimensions, you'll need recursion. As squint pointed out in a comment, making the above recursive is just a matter of giving our reduce callback a name and then doing reduce again instead of just using array.length:

var matrix = [1,2,3,4,5,6, [1,2,[3,4]]];
var sum = matrix.reduce(function callback(acc, entry) {
    return acc + (Array.isArray(entry) ? entry.reduce(callback, 0) : 1);
}, 0);
console.log(sum);


Some notes:

  • Array.isArray and Array#reduce were added in ES5 (in 2009) and so should be available in just about any modern browser (so, not IE8); they can both be shimmed/polyfilled on older browsers.
  • JavaScript doesn't actually have multi-dimensional arrays. It has arrays of arrays.
  • The recursive example above uses a construct called a named function expression for callback. NFEs have a bad name because years ago browsers got them wrong several different ways, but these days they're fine. (If you used the above on IE8 — including polyfills for the things it's missing — even it would work even though IE8 gets NFEs wrong.)
2 of 3
1

Building on @T.J. Crowder's solution with reduce, I would suggest to turn things around a bit so there is only one mention of reduce in the code. And to spice it up, this is with arrow syntax:

function entries(a) {
    return Array.isArray(a) ? a.reduce((acc, el) => acc + entries(el), 0) : 1;
}

var matrix = [1,2,3,4,5,6, [1,2, [3,4]]];

console.log(entries(matrix));

This way it will even work for non-array arguments: return value is 1 in that case. Obviously not that important.

Top answer
1 of 7
11

This recursive function returns all dimensions of a given array or false if one or more dimensions are not straight (i.e. different sizes between array items). It uses a helper function to determine whether two simple arrays are the same (read the function comments before using it).

// pre: a !== b, each item is a scalar
function array_equals(a, b)
{
  return a.length === b.length && a.every(function(value, index) {
    return value === b[index];
  });
};

function getdim(arr)
{
  if (/*!(arr instanceof Array) || */!arr.length) {
    return []; // current array has no dimension
  }
  var dim = arr.reduce(function(result, current) {
    // check each element of arr against the first element
    // to make sure it has the same dimensions
    return array_equals(result, getdim(current)) ? result : false;
  }, getdim(arr[0]));

  // dim is either false or an array
  return dim && [arr.length].concat(dim);
}

console.log(getdim(123)); // []
console.log(getdim([1])); // [1]
console.log(getdim([1, 2])); // [2]
console.log(getdim([1, [2]])); // false
console.log(getdim([[1, 2], [3]])); // false
console.log(getdim([[1, 2],[1, 2]])); // [2, 2]
console.log(getdim([[1, 2],[1, 2],[1, 2]])); // [3, 2]

console.log(getdim([[[1, 2, 3],[1, 2, 4]],[[2, 1, 3],[4, 4, 6]]])); // [2, 2, 3]

console.log(getdim([[[1, 2, 3], [1, 2, 4]], [[2, 1], [4, 4]]])); // false
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 7
2

Here is a simple recursive function to do that. Wrote it very quickly, so may prone to errors.

This function returns the lengths of each dimensions. If it contains sub-arrays of different lengths, this function returns false.

This function works for different dimensions.

For example, passing a 2d array of 2x3 will return [2, 3], a 3d array of 2x3x4 will return [2, 3, 4]. The dimension (i.e. n d) can be obtained by checking the length of the returned array.

// Array dimension checker
// Returns:
//   false when array dimensions are different
//   an Array when is rectangular 0d (i.e. an object) or >=1d
function arrayDimension(a) {
    // Make sure it is an array
    if (a instanceof Array) {
        // First element is an array
        var sublength = arrayDimension(a[0]);
        if (sublength === false) {
            // Dimension is different
            return false;
        } else {
            // Compare every element to make sure they are of the same dimensions
            for (var i = 1; i < a.length; i++) {
                var _sublength = arrayDimension(a[i]);
                // HACK: compare arrays...
                if (_sublength === false || sublength.join(",") != _sublength.join(",")) {
                    // If the dimension is different (i.e. not rectangular)
                    return false;
                }
            }
            // OK now it is "rectangular" (could you call 3d "rectangular"?)
            return [a.length].concat(sublength);
        }
    } else {
        // Not an array
        return [];
    }
}

Demo (Check the javaScript console :) )

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-multidimensional-array
JavaScript Multidimensional Array - GeeksforGeeks
Check Array Lengths: Always check the array's length before accessing its elements to avoid errors and undefined values. JavaScript does not have built-in support for multidimensional arrays like some other programming languages, but you can simulate them using nested arrays.
Published: July 12, 2025
Find elsewhere
🌐
freeCodeCamp
freecodecamp.org › news › javascript-2d-arrays
JavaScript 2D Array – Two Dimensional Arrays in JS
November 7, 2024 - Each element in the array is referred to as a cell and can be accessed by its row and column indices/indexes. [ a1, a2, a3, ..., an, b1, b2, b3, ..., bn, c1, c2, c3, ..., cn, . . . z1, z2, z3, ..., zn ] In JavaScript, there is no direct syntax for creating 2D arrays as with other commonly used programming languages like C, C++, and Java.
🌐
GitHub
gist.github.com › 4303229
Getting the dimensions of a multidimensional JS array. · GitHub
Getting the dimensions of a multidimensional JS array. - matrix-dimension.js
Top answer
1 of 2
1

You could reduce and recurse while keeping track of arrays that have been seen:

var depthCount = function(xss, depth) {
  depth = depth || 0
  var seen = []
  return xss.reduce(function(acc, xs) {
    if (Array.isArray(xs)) {
      return acc.concat(depthCount(xs, depth + 1))
    }
    if (seen.indexOf(xss) < 0) {
      seen.push(xss)
      return acc.concat({depth: depth, count: xss.length})
    }
    return acc
  }, [])
}

var xs = [1, 2, 3, 4, [5, [6], 7]]

console.log(depthCount(xs))
// [{depth: 0, count: 5},
//  {depth: 1, count: 3},
//  {depth: 2, count: 1}]

Then you can find out the total by filtering the collection by depth and checking the count. If you sum up the counts it will work when you have multiple arrays of the same depth too:

var xs = [1, [2, 3], [4, 5, [6, 7]]]

var count = depthCount(xs)

console.log(count)
// [{depth: 0, count: 3},
//  {depth: 1, count: 2},
//  {depth: 1, count: 3},
//  {depth: 2, count: 2}]

var countTotalDepth = function(depth, coll) {
  return coll.filter(function(obj) {
    return obj.depth === depth
  }).reduce(function(x, y) {
    return x.count + y.count
  })
}

console.log(countTotalDepth(1, count)) // 5
2 of 2
1

You can have a helper method get the count of members recursively, then use the main method to just access which layer count is wanted using "layer":

Pseudocode for helper function:

// Count members, and store if object
// Recursively get list of lengths from those objects
// Sum up those lists
    // find length of longest array
    // sum up all values, up to length of longest array
// Insert 'count' at front of the list
// Return

Full code:

/*
Main function
Returns a number: the count of members in a layer
*/
function getLength(layer, obj)
{
    return getAllLengths(obj)[layer];
}



/*
Helper function for getLength(..)
Returns an array
*/
function getAllLengths(obj)
{
    var count = 0; // for this layer's # of members
    var objectMembers = []; // list of members that are objects
    var objectsLists = []; // to store list of lists produced recursively from objectMembers
    var result = []; // to return


    // count, and store if object
    for (var mem in obj)
    {
        count++;
        if (obj[mem] instanceof Object)
        {
            objectMembers.push(obj[mem] );
        }
    }


    // recursively get objects' lists
    for (var i in objectMembers)
    {
        objectsLists.push(getAllLengths(objectMembers[i] ));
    }


    ////// sum up lists
    // find length of longest array
    var maxLength = 0;
    for (var i in objectsLists)
    {
        if (objectsLists[i].length > maxLength)
        {
            maxLength = objectsLists[i].length;
        }
    }
    // sum
    for (var i = 0; i < maxLength; i++)
    {
        var sum = 0;
        for (var j = 0; j < objectsLists.length; j++)
        {
            if (objectsLists[j][i] != undefined)
                sum += objectsLists[j][i];
        }
        result.push(sum);
    }


    // complete resulting list to return
    result.splice(0,0, count);

    return result;
}
🌐
DEV Community
dev.to › who_tf_cares › how-to-work-with-multidimensional-arrays-in-javascript-9jl
How to Work with Multidimensional Arrays in JavaScript - DEV Community
January 14, 2025 - Overview: Check the integrity of ... of nesting exists and contains the correct data types. Use conditionals or validation functions to check array length and structure....
🌐
Zenva
gamedevacademy.org › home › web development › frontend development › a useful introduction to javascript multidimensional arrays
A Useful Introduction To JavaScript Multidimensional Arrays - GameDev Academy
We can also notice that the first Array has three elements and the second has four elements. Let’s open it up further in the console to see inside the JavaScript multidimensional Array. The first Array is at index zero and the second Array is at index one. Also notice the length property of the main Array.
Published: October 21, 2023
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array
Array - JavaScript - MDN Web Docs
July 28, 2026 - JavaScript arrays are zero-indexed: the first element of an array is at index 0, the second is at index 1, and so on — and the last element is at the value of the array's length property minus 1.