I have the following code. I need to print only any Nested Arrays
.
let newArray = ["Ameen", "John", ["Working", "Studying"], [10, 100, 30, 40]];
for (let i = 0; i < newArray.length; i++) {
*// `Nested For Loop To Print The Nested Arrays`*
for (let j = 0; j <= i; j++) {
if (Array.isArray(newArray[i])) {
console.log(`Nested Array ${newArray[i][j]}`);
}
}
}
console.log(`Whole Array: ${newArray}`);
It’s working fine, however, the problem here is that the nested loop "j"
prints "undefined" after the last element of the first nested array ["Working", "Studying"]
.
I understand that because the index of "i"
is increased to "2"
, while the first nested array ["Working", "Studying"]
only has 2 elements which mean two indexes (0,1)
. Thus, the "j" can’t find the element with an index of "2"
within the first nested array.
The question is, how to make the nested loop "j" to not print "undefined" elements caused by the parent for loop index "i"?
4
Answers
After I squeezed my mind. I found the solution by adding another condition. Which is If the
newArray[i]
is anArray
and If (this is the added condition)newArray[i][j] !== undefined
as the followingIt's working as I wanted. However, I'm wondering if there is another way to achieve that. I appreciate your cooperation.
I think the could be simplified by doing the following
A solution that came to mind immediately that would prevent unnecessarily looping a second time would be:
Here are the nested sub arrays:
All the elements of the nested sub arrays: