Nima Nima - 1 year ago 98
Javascript Question

How can I detect multidimensional array length in javascript?

In the following code the matrix.length only counts the first array and not the second one. How can I count multidimensional array so the result for the following code is 10?

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

console.log(matrix.length - 1)

Answer Source

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

If you may have more dimensions, you'll need recursion.

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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download