DEV Community

loading...

Discussion on: Count Item Occurrences in an Array JavaScript Solution

Collapse
t0nyba11 profile image
Tony B

I was curious how fast this could go.
This seems to run 33% quicker than your solutions.
JavaScript still needs hand holding it seems. :)

const itemCounter = (array, item) =>
{
let count = 0;
const stack = [array];
while(stack.length > 0)
{
const x = stack.pop();
if(Array.isArray(x))
stack.push(...x)
else
count += (x === item);
}

return count;
}

Collapse
hellodevworldblog profile image
Hello Dev World Blog Author

I’m surprised that run 33% faster as it’s very similar to the first solution but it’s also possible that the .flat function isn’t super performant (wouldn’t surprise me) I’ll have to check that out tomorrow!

Collapse
hellodevworldblog profile image
Hello Dev World Blog Author • Edited

Interesting stack overflow comment on it stackoverflow.com/questions/614117...

If you were interested :)

The one below it is also interesting