Last active
September 26, 2018 16:56
-
-
Save mitrakmt/ccbeb40af03a49f98521b34391d44511 to your computer and use it in GitHub Desktop.
Exploring the programming interview question even occurrence in JavaScript.
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
// Prompt: Find the first item that occurs an even number of times in an array. Remember to handle multiple even-occurrence items and return the first one. Return null if there are no even-occurrence items. | |
function evenOccurrence (array) { | |
// Store counts | |
var storage = {}; | |
// Store each value within the storage object to keep count | |
array.forEach(function(value, index) { | |
storage[value] = storage[value] + 1 || 1; | |
}); | |
// loop through array to find first occurence of an even count | |
for (var i = 0; i < array.length; i++) { | |
var current = array[i]; | |
if (storage[current] % 2 === 0) { | |
return current; | |
} | |
} | |
// If no even occurrence found, return null | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment