Skip to content

Instantly share code, notes, and snippets.

@sonadztux
Created July 19, 2019 08:05
Show Gist options
  • Save sonadztux/ad20951391f2bfe08755999fb323dda8 to your computer and use it in GitHub Desktop.
Save sonadztux/ad20951391f2bfe08755999fb323dda8 to your computer and use it in GitHub Desktop.
A javascript function to counting duplicate of specific item/value in some array
const duplicateCounter = function (array, item) {
let itemLookingFor = [];
const arrayCopy = [...array]; // ES6 way to clone or copy an array to new array
arrayCopy.sort()
for (let i = 0; i < arrayCopy.length; i++) {
if(arrayCopy[i] === item) itemLookingFor.push(arrayCopy[i]);
}
return itemLookingFor.length;
}
/*
example use in console:
> const array = [5,6,1,4,5,7,8,2,4,6,3,2,6,6,3,5,5,2,10];
> duplicateCounter(array, 5);
Output:
<- 4
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment