Skip to content

Instantly share code, notes, and snippets.

@johnhutchins
Created September 19, 2019 14:06
Show Gist options
  • Save johnhutchins/17834e9b4a9c1f4025d57f08c423d072 to your computer and use it in GitHub Desktop.
Save johnhutchins/17834e9b4a9c1f4025d57f08c423d072 to your computer and use it in GitHub Desktop.
Find the array index where a passed in number should be between (IE, [1,2,4] with a 3 passed in should = [1,2,3,4]
function getIndexToIns(arr, num) {
let arrCopy = arr.sort(function(a, b){return a-b});
let lastIndexOfLowerNum = 0;
for(let i=0;i<arrCopy.length;i++){
if(num>arrCopy[i]){
lastIndexOfLowerNum = i + 1;
}
if(num === arrCopy[i]){
lastIndexOfLowerNum = i;
}
}
arrCopy.splice(lastIndexOfLowerNum,0,num);
return arrCopy.indexOf(num);
}
getIndexToIns([5, 3, 20, 3], 5) //should return 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment