0

I currently have a function below to find the first nonrepeating letter. For example, for the string carro, that letter would be c; for the string total, that letter would be o. I have the following code that works:

function findFirstNonrepeatedChar(str) {
  const store = {};
  const arr = str.split('');

  arr.forEach(item => {
    if(!store[item]) {
      store[item] = 1;
    } else {
      store[item] = store[item] + 1;
    }
  })
  
  for(let char in store) {
    if(store[char] === 1) return char;
  }
}

However, now I want to use a Map instead of just a plain object, and I'm having difficulty to update the frequency of the duplicate word like below:

function findFirstNonrepeatedChar(str) {
  const store = new Map();
  const arr = str.split('');

  arr.forEach(item => {
    if(!store.has(item)) {
      store.set(item, 1);
    } else {
      store[item]++;
    }
  })
  
  console.log(store, 'store')
  for(let char in store) {
    if(store[char] === 1) return char;
  }
}

What would be the best way to do so?

2
  • 1
    for the string total, that letter would be t, could you confirm this, because t occurs 2 time in total? Commented Jan 21, 2021 at 2:54
  • Sorry, that would be o Commented Jan 21, 2021 at 3:00

2 Answers 2

1

There are 2 things here:

  • you set to save the key-value to store, use get to get the value by key
    store.set(item, (store.get(item) || 0) + 1);
    
  • you iterate the key-value pairs of Map by for..of, not for..in

function findFirstNonrepeatedChar(str) {
  const store = new Map();
  const arr = str.split("");

  arr.forEach((item) => {
    store.set(item, (store.get(item) || 0) + 1);
  });

  for (let [char, occurrences] of store) {
    if (occurrences === 1) {
      return char;
    }
  }
}

console.log(findFirstNonrepeatedChar("carro"));
console.log(findFirstNonrepeatedChar("total"));

Sign up to request clarification or add additional context in comments.

Comments

0

Here's how I'd do it using Array.prototype.find() if you're interested in alternative solutions.

const findFirstNonrepeatedChar = (str) => str.split('').find(
  (val) => str.match(new RegExp(val, 'g')).length === 1
);

console.log(findFirstNonrepeatedChar('total'));
console.log(findFirstNonrepeatedChar("carro"));
console.log(findFirstNonrepeatedChar("aabbcc"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.