# Javascript Part 1 - 21 - Excerise 5 - (My Solution)

Well, another exercise I was able to complete on my own. Here is my solution which is totally different from Mosh’s solution not sure which one is better. I wasn’t able to do the last exercise (move an element) on my own which made me lose cofindence that i’m able to even think like a coder in the first place. But, being able to solve this one on my own even though it may not be optimal or correct it does what its suppose to do count how many elements are in said array.

It only works with bools, numbers and strings. It doesn’t work with objects inside the array and not even sure how to even think of doing that .

Anyways…

My Solution

``````const numbers = [1, 2, 3, 4, 1, 5, 7, 2, 1, 4, 5, 6, 2, 1, 5, 6, 2];

function countOccurrences(array, searchElement){
const numOfElements = array.filter(element => element === searchElement);
return numOfElements.length;
}

console.log(countOccurrences(numbers, 2));
``````

Mosh’s Solution(Either Solution 1 or 2)

``````const numbers = [1, 2, 3, 4, 1, 5, 7, 2, 1, 4, 5, 6, 2, 1, 5, 6, 2];

function countOccurrences(array, searchElement){

// Solution 1
let count = 0;
for(let element of array)
if(element === searchElement)
count++;
return count;
//

// Solution 2
return array.reduce((acc,curr) => {
const occurences = (curr === searchElement) ? 1 : 0;
return acc + occurences;
}, 0);
}
console.log(countOccurrences(numbers, 2));``````

Since your solution returns the right results it’s correct. It’s also small and easy to understand.

Mosh’s solutions are more efficient since they don’t create a new array - think of a really big input array with lots of occurences of the element to search for. But as long as the result is correct you can always come back to refactor your function in case memory usage becomes an issue.

Pay attention to naming. When I read `numOfElements` I’d expect the variable to hold a number not an array.

1 Like