Skip to content

Instantly share code, notes, and snippets.

@Liampronan
Last active April 3, 2022 18:18
Show Gist options
  • Save Liampronan/6922705 to your computer and use it in GitHub Desktop.
Save Liampronan/6922705 to your computer and use it in GitHub Desktop.
//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