Created
October 15, 2020 21:53
-
-
Save Gerst20051/09c408f8a1bf53f158dc80bff30bd08f to your computer and use it in GitHub Desktop.
Find First Unique Character In String
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 findUniqueCharacter(string) { | |
const characterMap = buildCharacterMap(string); | |
return findFirstUniqueCharacterInMap(characterMap); | |
} | |
function buildCharacterMap(string) { | |
return string.split('').reduce((map, character) => { | |
if (!map[character]) { | |
map[character] = 1; | |
} else { | |
map[character]++; | |
} | |
return map; | |
}, {}); | |
} | |
function findFirstUniqueCharacterInMap(characterMap) { | |
const characters = Object.keys(characterMap); | |
for (let i = 0; i < characters.length; i++) { | |
if (characterMap[characters[i]] === 1) { | |
return characters[i]; | |
} | |
} | |
return '_'; | |
} | |
const firstUniqueCharacter = findUniqueCharacter('stringgoeshere'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment