DEV Community 👩‍💻👨‍💻

Matheus Costa
Matheus Costa

Posted on

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

Top comments (5)

Collapse
 
frankwisniewski profile image
Frank Wisniewski • Edited on

simplify it by using xor

const lonelyInteger = x => x.reduce( ( a, c ) => a^c )

console.log(
    lonelyInteger( [1,2,4,2,1] )
)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
costamatheus97 profile image
Matheus Costa

Way more simpler indeed, thanks for the tip Frank!

Collapse
 
paschalyn1 profile image
Ukwuani Paschalyn

A very simple process indeed. Well done

Collapse
 
paschalyn1 profile image
Ukwuani Paschalyn • Edited on
function lonelyInteger(arr){
    arr = arr.sort();
    // 1 1 2 2 3 3 4
    //sort tthe array to get it in the right order, to be able to check the one that does not repeat.
    let result;
    for(let i = 0; i < arr.length; i++){
        if(arr[i] !== arr[i + 1] || arr[i] !== arr[i - 1]){
            result = arr[i];
        }
        //check if the element in front and the elemenet at the back of the arr[i] element are the same if not then that means the element is alone since this is a sorted array.
    }
    return result;

    //return the result from the loop.
}
console.log(lonelyInteger([1, 2, 3, 4, 5, 6, 7, 6, 5 , 4, 5, 3, 2, 1]));
//console.log the function and write down the answers.
Enter fullscreen mode Exit fullscreen mode

`

Collapse
 
paschalyn1 profile image
Ukwuani Paschalyn • Edited on

You can check this out too if you are looking for an explicit process that is self-explanatory too.

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.