functionlonelyinteger(a){// destructure the first (and only) element, sort then reduceconst[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 arrayif(!acc.includes(curr)){// if not, we'll add itacc.push(curr)}else{// if so, we'll remove the last element.// This way we'll be removing all duplicatesacc.pop()}// return the array to the next iterationreturnacc},[])returnlonely}
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.
Top comments (5)
simplify it by using xor
Way more simpler indeed, thanks for the tip Frank!
A very simple process indeed. Well done
`
You can check this out too if you are looking for an explicit process that is self-explanatory too.