Last active
April 15, 2017 15:24
-
-
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)
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
/** | |
*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; | |
}; |
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
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