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
}
``````

## Latest comments (5)

``````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.
``````

`

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

Frank Wisniewski • Edited

simplify it by using xor

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

console.log(
lonelyInteger( [1,2,4,2,1] )
)
``````

Ukwuani Paschalyn

A very simple process indeed. Well done

Matheus Costa

Way more simpler indeed, thanks for the tip Frank!

DEV Community

Need a better mental model for async/await?

Check out this classic DEV post on the subject.