Created
September 27, 2021 10:53
-
-
Save Stefanacef/f75fff072a4278066f780c5c05dbfcd7 to your computer and use it in GitHub Desktop.
Count the number of times a value appears in a JavaScript array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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