Lonely Integer - Hackerrank Challenge in Javascript

costamatheus97

Matheus Costa

Posted on June 22, 2022

Lonely Integer - Hackerrank Challenge in Javascript
function lonelyinteger(a) {

    // destructure the first (and only) element, sort then reduce
    const [lonely] = a.sort((a, b) => a - b).reduce((acc, curr) => {      
        // here we'll start the reduce with an empty array and check
        // if the current integer is already on the array
        if(!acc.includes(curr)) {
            // if not, we'll add it
            acc.push(curr)
        } else {
            // if so, we'll remove the last element.
            // This way we'll be removing all duplicates
            acc.pop()
        }

        // return the array to the next iteration
        return acc
    }, [])

    return lonely
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
costamatheus97
Matheus Costa

Posted on June 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related