return the first non repeating character in a string in javascript

后端 未结 26 2213
清酒与你
清酒与你 2020-12-30 09:04

So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.

T

相关标签:
26条回答
  • 2020-12-30 09:33
    let str = 'aabbcdd';
    let val = str.split('').reduce((a, e)=>{ if(str.indexOf(e) == str.lastIndexOf(e)) {a = e }; return a})
    console.log(val); // c
    
    0 讨论(0)
  • 2020-12-30 09:35

    Here is another approach:

    Everytime you find equal chars store it in an array and break out of the loop. If the char is not found in the array then you have your first nonRepeating char

    function nonRepeatingChars(value) {
      const memory = []
      for (let i = 0; i < value.length; i++) {
        for (let j = i + 1; j < value.length; j++) {
          if (value[i] === value[j]) {
            memory.push(value[j])
            break;
          }
        }
        if (!memory.some(x => x === value[i])) {
          return value[i];
        }
      }
      return "all chars have duplicates";
    }
    
    console.log('First non repeating char is:',nonRepeatingChars("esen"))
    console.log('First non repeating char is:',nonRepeatingChars("esesn"))
    console.log('First non repeating char is:',nonRepeatingChars("eseulsn"))
    console.log('First non repeating char is:',nonRepeatingChars("esesnn"))

    0 讨论(0)
提交回复
热议问题