Skip to content

Instantly share code, notes, and snippets.

@matfin
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matfin/5202ac2be91bc1e195d7 to your computer and use it in GitHub Desktop.
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.
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