JSFiddle - React, Tailwind, and code Playground

by asemahle

JavaScript

function idxFirstNonRepeatingChar(str) {
	str = str.toLowerCase()
	const map = {}
  let idx = 0
  for (let char of str) {
  	if (map[char] != null) {
    	map[char].count++
    }
    else {
    	map[char] = {
      	count: 1,
        index: idx
      }
    }
    idx++
  }
  let bestIndex = -1
  for (let char in map) {
  	let currIndex = map[char].index
    let currCount = map[char].count
  	if (currCount === 1 && (bestIndex === -1 || currIndex < bestIndex)) {
    	bestIndex = currIndex
    }
  }
  return bestIndex
}

console.log(idxFirstNonRepeatingChar('Toronto'))
console.log(idxFirstNonRepeatingChar('abcdefg'))
console.log(idxFirstNonRepeatingChar('aabbcdcd'))