How to properly count occurrence in arrays?

Viewed 387

I've got an in depth array (arrays of arrays). I'm trying to make a decent function without using any extra methods and JS designs (like closures).

This is a working solution (but a bad one because of the global variable)

  var counter = 0;

  function findArray(array, item) {
      for (var i = 0; i < array.length; i++) {
          if (array[i] == item) {
              counter++;
          } else if (array[i].constructor === Array) {
              findArray(array[i], item);
          }
      }
      return counter;
  }

This is a none working solution with trying to avoid the global counter variable.

  function findArray(array, item, counter) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == item) {
            ++counter;
        }
        if (array[i].constructor === Array) {
            findArray(array[i], item, counter);
        }
    }
    return counter;
}

I would also like to avoid the counter input parameter since parameters should only be inputs and output variables shouldn't be inside the function params. Also I would like to avoid built in methods for instance slice etc.

NOTE: The optimal performance of the algorithm should not be taken into consideration.

Is there a way to make this work with the counter being inside the function?

function call looks like this:

findArray([1,[1,2,3],1,[5,9,1],6],  1,0);

The output should be number 4, in this example (integer 1 is the number to be searched in the array).

5 Answers

Another, maybe more comprehensible solution:

function sumValues(array) {
    let counter = 0;
    for (let item of array) {
      if (Array.isArray(item)) {
        counter += sumValues(item);
      }
      else {
        counter += item;
      }
    }
    return counter;
  }
Related