Skip to content

Instantly share code, notes, and snippets.

@swaraj89
Last active April 15, 2017 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swaraj89/181846cbaaee246f0757f1ea2016c1a8 to your computer and use it in GitHub Desktop.
Save swaraj89/181846cbaaee246f0757f1ea2016c1a8 to your computer and use it in GitHub Desktop.
JS array polyfill to get all occurrence of an item in a array. (while loop and for Loop)
/**
*Simpler solution using for loop; without using any array.indexOf()
*/
Array.prototype.getIndicesOf = function(item){
var indices = [];
for(var i=0; i < this.length; i++){
if(this[i] === item){
indices.push(i);
}
}
return indices;
};
Array.prototype.getIndicesOf = function(item){
var indices = [];
var currentIndex = 0;
while(currentIndex != -1){
currentIndex = this.indexOf(item, currentIndex);
if(currentIndex != -1) {
indices.push(currentIndex);
currentIndex++;
}
}
return indices;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment