I\'ve been trying to iterate over a multidimensional array in JavaScript, and print each element in the array. Is there any way to print each element in a multidimensional a
If you don't want to use nested loops, you can either flat the array or use a recursive function. Something like:
arr.forEach(function each(item) {
if (Array.isArray(item))
item.forEach(each);
else
console.log(item)
});
Sounds like the issue is that you may have a nesting of arbitrary depth. In that case, use a recursive function.
function printArray(arr) {
for (var i = 0; i < arr.length; i++)
if (Array.isArray(arr[i]))
printArray(arr[i])
else
console.log(arr[i])
}
The Array.isArray
will need a shim for older browsers.
if (!Array.isArray)
Array.isArray = function(o) {
return !!o && Object.prototype.toString.call(o) === "[object Array]"
}