How to find the first non-repeated character in a string with TypeScript

2 Answers

0 votes
function getFirstNonRepeatedCharacter(s: string) : string | null {
    let length: number = s.length;
     
    for (let i: number = 0; i < length; i++) {
        if(s.indexOf(s[i]) === s.lastIndexOf(s[i])) {
            return s[i];
        }
    }
     
    return null;
}
  
const s = 'typescript programming';
  
console.log(getFirstNonRepeatedCharacter(s));
  
  
  
/*
run:
  
"y"
  
*/

 



answered Jun 28, 2025 by avibootz
0 votes
function getFirstNonRepeatedCharacter(s: string): string | null {
    for (let ch of s) {
        if ([...s].filter(c => c === ch).length === 1) {
            return ch;
        }
    }
    return null;
}

console.log(getFirstNonRepeatedCharacter("typescript programming")); 
  
  
  
/*
run:
  
"y"
  
*/

 



answered Jun 28, 2025 by avibootz
...