// Дан отсортированный по возрастанию массив arr и число target.
// Нужно найти индекс первого появления числа target.
 
function findFirstMatch(arr, target) {
let left = 0;
let right = arr.length - 1;
let currentIndex = null;
 
while (left <= right) {
const middleIndex = Math.floor((right + left) / 2);
 
if (arr[middleIndex] < target) {
left = middleIndex + 1;
} else {
if (arr[middleIndex] === target) {
currentIndex = middleIndex;
}
right = middleIndex - 1;
}
}
 
return currentIndex;
}
 
console.log(findFirstMatch([10, 20, 30, 40, 40, 50, 60, 70], 40));
 
Click Run to execute JavaScript.
Code runs in an isolated environment.