firstNotRepeating

with Carmen Salas • 2024/11/05

Non-object Approach

/*
**Problem**
Find the first non-repeating [char] in an input [string].

**Examples/Edge Cases:** 
"meow" -> "m"
"meowmoe" -> "w""

**Data Structures**
- Arrays
- Strings

**Algorithm** 
- loop through every [char] in the [string]:
  - return result as soon as first index is not equal to last index of specific [char]
- if not found, return '_'
*/

// Same approach with HW: swe-1-2/from-scratch.js/hasOnlyOneOfThisLetter (Question #7)
function solution(s) {
  // one-liner
  return [...s].find(char => s.indexOf(char) === s.lastIndexOf(char)) || '_';
  
  // for-loop, more readable
  for (const char of s) {
    if (s.indexOf(char) === s.lastIndexOf(char)) {
      return char;
    }
  }
  return '_';
}

Last updated