Last active
April 3, 2022 18:18
-
-
Save Liampronan/6922705 to your computer and use it in GitHub Desktop.
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
//find first occurrence of a char in a given word | |
function first_unique_char(word) | |
{ | |
letter_obj = new Object(); | |
word_array = word.split(''); | |
//first setup hash to store occurrences of char | |
for (var letter in word_array){ | |
if (letter_obj[word_array[letter]] === undefined){ | |
letter_obj[word_array[letter]] = 1;} | |
else{ | |
letter_obj[word_array[letter]] = letter_obj[word_array[letter]] + 1;} | |
} | |
//loop through second time and exit when char is | |
//unique (i.e., hash value == 1) | |
for (var letter in word_array){ | |
if (letter_obj[word_array[letter]] == 1){ | |
return [word_array[letter]];} | |
} | |
} | |
console.log(first_unique_char('google')); | |
console.log(first_unique_char('123454321')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment