Last active
August 29, 2015 14:26
-
-
Save matfin/5202ac2be91bc1e195d7 to your computer and use it in GitHub Desktop.
Iterate through and array and return the first number that occurs an odd number of times.
This file contains hidden or 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
var numbers = [1, 1, 2, 3, 2, 3, 7, 8, 8]; | |
var getOddOccurrence = function(numbers) { | |
var collected = [], | |
keys, | |
oddnum; | |
numbers.forEach(function(number) { | |
if(typeof collected[number] === 'undefined') { | |
collected[number] = []; | |
} | |
collected[number].push(number); | |
}); | |
keys = Object.keys(collected); | |
keys.forEach(function(key) { | |
if(collected[key].length % 2 !== 0) { | |
oddnum = collected[key][0]; | |
} | |
}); | |
return oddnum; | |
}; | |
getOddOccurrence(numbers); //should log 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment