1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
let arr = [1,5,6,7,9,10]
function getCurrentIndex(arr,current) { let newArr = [...arr] newArr.sort((a,b)=> a-b) let cIndex = 0 let endIndex = newArr.length - 1 while(cIndex <= endIndex) { let middleIndex = Math.floor((cIndex + endIndex) / 2) if(current < newArr[middleIndex]) { endIndex = middleIndex - 1 }else if(current > newArr[middleIndex]) { cIndex = middleIndex + 1 }else { return middleIndex } } return -1 }
getCurrentIndex(arr,5)
|