JSFiddle - React, Tailwind, and code Playground
HTML
<div id="msg"></div>
JavaScript
// Define our array.
var a = [];
a[0] = [
['1', '2', '3'],
['4', '5', '6'],
['7', '8', '9']
];
a[1] = [
['10', '11'],
['12', '13', '14']
];
a[2] = [
['15', '16', '17'],
['18'],
['19', '20']
];
a[3] = [
['21', '22', '23']
];
/* Sums the number of elements in each subarray of the given array.
Returns the resulting sum.
array: the array to count the elements of. */
function countAllElements(array) {
var elements = 0;
if (Array.isArray(array)) {
for (var i = 0; i < array.length; ++i) {
elements += countElements(array[i]);
}
}
else {
++elements;
}
return elements;
}
/* Sums the number of elements in each subarray of the given array up to the given target index.
Returns the resulting sum.
array: the array to count the elements of.
target: the target index as an array, e.g. [3, 1, 5].
depth: current depth in the nested arrays. Do not call with this. */
function countElementsBeforeIndex(array, target, depth) {
var elements = 0;
depth = depth || 0;
if (Array.isArray(array)) {
for (var i = 0; i < target[depth]; ++i) {
elements += countAllElements(array[i]);
}
elements += countElementsBeforeIndex(array[target[depth]], target, depth + 1, i);
}
return elements;
}
// Let's test this.
for (var i = 0; i < a.length; i++) {
for (var j = 0; j < a[i].length; j++) {
for (var k = 0; k < a[i][j].length; k++) {
var n = countElements2(a, [i, j, k]);
$("<div>").text([i, j, k] + ": " + n).appendTo($("#msg"));
}
}
}