I am trying to build a function to visit every value in a multi-dimensional array that has no limit to dimensions.
The depth of each value is generated.
var array = [[0, [[1, [2, [3, []]]],[4, []],[5, [6, []]],[7, [8, [9, []]]],[10, []]]]];
function visitall(a) {
for (i = 0; i < (a.length); i++) {
console.log(a[i][0])
for (j = 0; j < (a[i][1].length); j++) {
console.log(a[i][1][j][0])
for (n = 0; n < (a[i][1][j][1].length); n++) {
console.log(a[i][1][j][1][n][0])
}
}
}
}
visitall(array)
You can use recursion.
Use Array.isArray to check if variable is array. If it is, do a forEach and call the visitall function again.
function visitall(a) {
if (Array.isArray(a)) a.forEach(visitall);
else console.log(a); //Not an array, so console.log
}
var array = [[0, [[1, [2, [3, []]]],[4, []],[5, [6, []]],[7, [8, [9, []]]],[10, []]]]];
visitall(array);
Or you can join, split and filter so you can get all the number in the array. You can now loop as normal.
var array = [[0, [[1, [2, [3, []]]],[4, []],[5, [6, []]],[7, [8, [9, []]]],[10, []]]]];
var result = array.join().split(',').filter(o => o !== '');
console.log(result);
just use recursion
var array = [
[0, [[1, [2, [3, []]]], [4, []], [5, [6, []]], [7, [8, [9, []]]], [10, []]]]
];
function visit(a) {
if (Array.isArray(a)) {
for (let i = 0; i < a.length; i++) visit(a[i]);
} else {
console.log(a);
}
}
visit(array);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With