I have an array of depth (arrays of arrays). I am trying to make a decent function without using any additional JS methods and constructs (e.g. closures).
This is a working solution (but bad due to a 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 working solution of none with an attempt 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 parameter of the input parameter of the counter , since the parameters should be only inputs, and the output variables should not be inside the parameters of the function. Also, I would like to avoid inline methods like slice, etc.
NOTE. The optimal performance of the algorithm should not be taken into account.
?
:
findArray([1,[1,2,3],1,[5,9,1],6], 1,0);
4, ( 1 - , ).