I'm writing a function that receives an array and returns an object with the count of unique values, pretty much like other questions here or in StackExchange. Except that in my case, this array may contain a nested array, like:
var array = [1, 2, 'a', 'b', [3, 'c', 1], 'd', 2, 'b'];
Here is my code:
function findUniques(array, occurrences) {
if (!occurrences) {
occurrences = {};
}
//checking if parameter passed is an array
if (Array.isArray(array)) {
for (let i = 0; i < array.length; i++) {
//if item is a nested array, call findUniques again
if (Array.isArray(array[i])) {
occurrences = findUniques(array[i], occurrences);
} else {
//add to/update count in occurrences object
occurrences[array[i]] = occurrences[array[i]] + 1 || 1;
}
}
}
return occurrences;
}
It's returning the following object, as it was supposed to:
{
'1': 2,
'2': 2,
'3': 1,
a: 1,
b: 2,
c: 1,
d: 1
}
My worry is that I'm using recursion.
Is it possible to optimize this function?
(Bear in mind that I must only use vanilla JavaScript)