Skip to content

Instantly share code, notes, and snippets.

@Stefanacef
Created September 27, 2021 10:53
Show Gist options
  • Save Stefanacef/f75fff072a4278066f780c5c05dbfcd7 to your computer and use it in GitHub Desktop.
Save Stefanacef/f75fff072a4278066f780c5c05dbfcd7 to your computer and use it in GitHub Desktop.
Count the number of times a value appears in a JavaScript array
let arr = [3, 2, 1, 3];
function countDuplicate(arr) {
let number = 0;
arr.find((item, index) => {
if (arr.indexOf(item) !== index) {
number=item // find the duplicate (return 3)
}
});
// you can use just the function below if you know the exact value for the duplicate
function getOccurrence(array, value) {
let count = 0;
array.forEach((v) => (v === value && count++));// get how many times as the duplicate appeared
return count; //(return 2 because 3 appeared 2 times)
}
return (getOccurrence(arr,number))
}
console.log(countDuplicate(arr)) // console.log 2 becuase
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment