Created
September 19, 2019 14:06
-
-
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]
This file contains hidden or 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
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