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)
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)
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.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.)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.
As of 2019 the answers using reduce are deprecated (or at least there is a better solution to solve it). Make use of the Array.flat() method to "flatten" the array and take the length of it:
var matrix = [1,2,3,4,5,6, [1,2,3,4]];
// this will return you 10
console.log("Length of multidimensional array items: " matrix.flat().length)