A
A
Atheist212020-09-03 06:28:48
JavaScript
Atheist21, 2020-09-03 06:28:48

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]]]));


But this is too clumsy, I want the variable to be set inside the function. I'm trying to use the features of ES6, the variable is updated every time the function itself is called. What am I doing wrong? What to pay attention to? How to correctly set variables during recursion so that it does not update?
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

1 answer(s)
D
Dmitry Kulakov, 2020-09-03
@Atheist21

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 question

Ask a Question

731 491 924 answers to any question