Skip to content

Instantly share code, notes, and snippets.

@BolajiAyodeji
Created March 3, 2019 20:45
Show Gist options
  • Save BolajiAyodeji/db6e545dfc434c7402d10cb2a13759a3 to your computer and use it in GitHub Desktop.
Save BolajiAyodeji/db6e545dfc434c7402d10cb2a13759a3 to your computer and use it in GitHub Desktop.
Count occurence of a number in an array with Error Handling
function countOccurences(array, searchElement) {
if (!Array.isArray(array)) {
throw new Error('Enter a valid array');
}
return array.reduce((accumulator, current) => {
const occurence = (current === searchElement) ? 1 : 0;
return accumulator + occurence;
}, 0)
}
try {
const numbers = null;
const count = countOccurences(numbers, 1);
console.log(count);
}
catch(e) {
console.log(e.message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment