Skip to content

Instantly share code, notes, and snippets.

@fazeelanizam13
Created May 10, 2022 08:57
Show Gist options
  • Save fazeelanizam13/f0cebb6ce86abb0a102fe1c933c8bda5 to your computer and use it in GitHub Desktop.
Save fazeelanizam13/f0cebb6ce86abb0a102fe1c933c8bda5 to your computer and use it in GitHub Desktop.
function firstUniqueCharacter(text) {
// split string into single characters
let characters = String(text).split("")
if (characters.length < 1) return 'Please input a non-empty string'
// iterate through array, comparing each character to the rest
// if found no match for a certain character after comparing to all other characters, return character at the end of first such iteration
// for chatacters being compared
for (let i = 0; i < characters.length; i++) {
// for characters being compared with
for (let j = 0; j < characters.length; j++) {
// if not comparing to self
if (!(i === j)) {
// AND if similar, jump to next character to compare with the rest - as it's a repeat
if (characters[i] === characters[j]) break
}
// if has come to the last character (also means we haven't found a match above)
// return this character
if (j === (characters.length - 1)) {
return characters[i]
}
}
}
}
console.log(firstUniqueCharacter('what is life'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment