How to show which number (from two number) is closer to a specific number in JavaScript?number

Hi everyone,

How can I create a function that takes 3 parameters such as:

const compareNumber = (userGuess, computerGuess, secretGuess)

I need to determine which player wins whoever is closer to the secretGuess number.
If userGuess win, return true and if computerGuess win, return false.

Is there any sort of comparison operator to create such a function?
Thanks

I did not really spend much time on this at all, so you can build and optimize as you see fit.

function getClosest(target, array) {
    
    const firstABS = Math.abs(target - array[0]); 
    const secondABS = Math.abs(target - array[1]); 

    if (firstABS < secondABS) {
        return array[0];
    } else if (firstABS > secondABS) {
        return array[1];
    }

    return array;
} 

const target = 5;
const playerOneGuess = 1;
const playerTwoGuess = 9;
const playerGuesses = [playerOneGuess, playerTwoGuess];
const closer = getClosest(target, playerGuesses);

if (closer.length === 2) {
    console.log("It's a tie"); 
} else if (closer === playerOneGuess) {
    console.log("player 1 wins")
} else {
    console.log("player 2 wins");
}
1 Like