Skip to content

Instantly share code, notes, and snippets.

@rashed-jitu
Last active September 11, 2016 07:13
Show Gist options
  • Save rashed-jitu/f0807cd846f1e1c2b7886c3979c1b06c to your computer and use it in GitHub Desktop.
Save rashed-jitu/f0807cd846f1e1c2b7886c3979c1b06c to your computer and use it in GitHub Desktop.
Find all indexes of an item of an array with javascript(js)
var array = ['hi','asdfa','ti' , 'rad' , 'hi' , 'asasd' , 'hi'];
function itemIndexs(array){
this.array = array;
this.findIndexs = function(item){
var tempArray = this.array , indexes = [];
while(tempArray.indexOf(item) >= 0){
var firstOcarence = tempArray.indexOf(item) , lastOcarence = tempArray.lastIndexOf(item);
if(firstOcarence == lastOcarence){
indexes.push(firstOcarence + 1);
tempArray[firstOcarence] = null;
}else{
indexes.push(firstOcarence+1);
indexes.push(lastOcarence+1);
tempArray[firstOcarence] = null;
tempArray[lastOcarence] = null;
}
}
return indexes.length > 0 ? indexes : false;
};
};
var newArrayObject = new itemIndexs(array);
console.log(newArrayObject.findIndexs("hi"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment