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

🌐
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
🌐
SitePoint
sitepoint.com › javascript
Multidimensional Array Length - JavaScript - SitePoint Forums | Web Development & Design Community
July 9, 2010 - Since JavaScript doesn’t have multi-dimensional arrays there is no such thing as multi-dimensional array length in JavaScript.
🌐
W3Schools
w3schools.com › jsref › jsref_length_array.asp
JavaScript Array length Property
The length property sets or returns the number of elements in an array.
🌐
Mimo
mimo.org › glossary › javascript › array-length
JavaScript Array Length: Master Data Handling
The JavaScript array length property provides the number of elements in an array.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › length
Array: length - JavaScript - MDN Web Docs
The length data property of an Array instance represents the number of slots in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array. It may be greater than the number of elements if the array is sparse.
🌐
CodingNomads
codingnomads.com › javascript-array-length
JavaScript Array Length Property
Discover the JavaScript arrays length property to get array size and access the last element seamlessly.
🌐
Jsremote
jsremote.jobs › tutorials › array_size
Array method size() in JavaScript | Web developer jobs
December 30, 2022 - We should begin by saying that the size() method is not fully valid. It is not a native array method. If you really want to use the size() method, you need to connect additional libraries. For example size() is available in JQuery and other libraries, not in JavaScript.
🌐
freeCodeCamp
freecodecamp.org › news › javascript-array-length-tutorial
JavaScript Array Length – How to Find the Length of an Array in JS
September 4, 2024 - The length of an array tells us how many elements are present in the array. You can use this to check if an array is empty and, if not, iterate through the elements in it. Javascript has a <.length> property that returns the size of an array as a number(integer).
🌐
TutorialsPoint
tutorialspoint.com › javascript › array_length.htm
JavaScript - Array length Property
The length property of an array in JavaScript returns the number of elements in the array.
🌐
GitHub
github.com › stdlib-js › array-shape
GitHub - stdlib-js/array-shape: Determine (nested) array dimensions. · GitHub
var arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; var shape = arrayShape( arr ); // returns [ 3, 3 ] The function ignores inconsistent dimensions.
Author: stdlib-js
🌐
Vultr Docs
docs.vultr.com › javascript › standard library › array › length
Get Array Length - JavaScript
September 27, 2024 - By setting colors.length = 4, the array now has two additional undefined slots, increasing the total length to four. The length property of JavaScript arrays is a powerful attribute that you can leverage to manage array sizes and manipulate their content.
🌐
YouTube
youtube.com › watch
JavaScript Basics - How To Find The Length Of An Array - YouTube
In this tutorial I'll show you how to find the length of an array in JavaScript.-------------------------------------------------------------------All my JS ...
Published: November 17, 2024
🌐
YouTube
youtube.com › watch
How to calculate array.length in large Arrays in JavaScript ! - YouTube
In this video, you will learn how to calculate array.length in large Arrays in JavaScript !🔔 Subscribe for more videos like this : https://www.youtube.com/c...
Published: September 30, 2024
🌐
freeCodeCamp
freecodecamp.org › news › javascript-2d-arrays
JavaScript 2D Array – Two Dimensional Arrays in JS
November 7, 2024 - A two-dimensional array, also known as a 2D array, is a collection of data elements arranged in a grid-like structure with rows and columns. Each element in the array is referred to as a cell and can be accessed by its row and column indices/indexes.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-multidimensional-array
JavaScript Multidimensional Array | GeeksforGeeks
JavaScript does not have built-in support for multidimensional arrays like some other programming languages, but you can simulate them using nested arrays. This approach allows you to work with grids, matrices, or even higher-dimensional data structures.
Published: April 24, 2025
🌐
Medium
medium.com › @himanshu_tanwar › create-multidimensional-array-in-javascript-8480a61c863d
Create Multidimensional Array in JavaScript | by Himanshu Tanwar | Medium
April 21, 2023 - Create Multidimensional Array in JavaScript In Javascript, creating a single dimensional array is very straightforward. You can use the square brackets to create one or use the Array constructor to …