How to find the digit previous to a given digit in a number with JavaScript

1 Answer

0 votes
// Finds the digit that comes before the target digit when scanning from right to left.

function findPreviousDigit(number, target) {
    while (number > 0) {
        const current = number % 10;
        number = Math.floor(number / 10);

        if (current === target) {
            return number > 0 ? number % 10 : -1;
        }
    }

    return -1;
}

const number = 8902741;
const target = 7;

const result = findPreviousDigit(number, target);

if (result !== -1) {
    console.log(`The digit before ${target} in ${number} is ${result}.`);
} else {
    console.log(`The digit ${target} is not found or has no previous digit in ${number}.`);
}


/*
run:

The digit before 7 in 8902741 is 2.

*/

 



answered Oct 21, 2025 by avibootz
...