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…
Let me know your thoughts
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));