Created
October 7, 2017 19:59
-
-
Save unilecs/25803cf8c0b2587c2de8ccb8fea451ad to your computer and use it in GitHub Desktop.
Get number w/o pair in the array of numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function getUniqueNumberInArray(arr) { | |
if (!arr || !arr.length) { | |
return null; | |
} | |
let result = arr[0]; | |
for (let i=1; i<arr.length; i++) { | |
result ^= arr[i]; // XOR each element in array | |
} | |
return result; | |
} | |
const arr = [ 0, 4, -1, 5, -1, 4, 0 ]; | |
console.info(getUniqueNumberInArray(arr)); |
Borzilov, good point.
But I try don't any cool functions from the "box" of language. Here it will be syntactic sugar and will not affect the algorithm itself.
The decision should be understood even by those who do not know the language
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe for-loop could be changed to:
arr.reduce( (result, element) => result ^ element )