Answer the question
In order to leave comments, you need to log in
How to count the number of rows in a nested structure?
There is an array or an object of various nesting, the task is to count all the available inline elements in it. I solved it by setting the line counter as a global variable.
let countString = 0;
function getStringCount(object) {
for (let i in object) {
if (typeof object[i] === "object") {
getStringCount(object[i]);
} else {
if (typeof object[i] === "string") {
countString++;
}
}
}
return countString;
}
console.log(getStringCount([1, 2, 3, "1", ["1", 1, ["f", 1]]]));
function getStringCount(object, countString) {
countString = countString || 0;
for (let i in object) {
if (typeof object[i] === "object") {
getStringCount(object[i], countString);
} else {
if (typeof object[i] === "string") {
countString++;
}
}
}
return countString;
}
Answer the question
In order to leave comments, you need to log in
Create another function inside this function that will call this loop, something like this.
function getStringCount(obj) {
let countString = 0;
function foo(object) {
for (let i in object) {
if (typeof object[i] === "object") {
foo(object[i]);
} else {
if (typeof object[i] === "string") {
countString++;
}
}
}
}
foo(obj)
return countString;
}
console.log(getStringCount([1, 2, 3, "1", ["1", 1, ["f", 1]]]))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question