1

I am trying to find a unique word in my input string with JS and have written a code. However, my code doesn't work and I don't know why. Could anyone help me please?

function findUniqueWord(index){
    var show = []
    var result = [...index]
    for (let i = 0; i < result.length; i++) {
        for (let j = i + 1; j < result.length; j++) {
            if(result[i] === result[j]){
                
            }
            else{
                return show.push(result[i])
            }
            
        } 
    }
    return show
}

console.log(findUniqueWord('A2A'));

5
  • 3
    What does "find a unique word" mean? What do you expect findUniqueWord('A2A') to return? Commented Jan 17, 2022 at 20:57
  • 2
    What exactly are you trying to achieve? You've only provided one word in the input, so it's always unique. Commented Jan 17, 2022 at 20:57
  • The thing is I am looking for the first character in my input which is string that is unique and is not duplicated. For example, if I enter 'Mystery' the out put be just the first unique character or 'M'. Commented Jan 17, 2022 at 21:09
  • Your code accepts an array as parameter, but based on your example, I assume your goal is to work with a string instead and find the first unique character in the string? Commented Jan 17, 2022 at 21:41
  • @MahmoudMohammadnezhad Have you try my answer? Commented Jan 24, 2022 at 13:34

1 Answer 1

1

If you intend to find the first unique letter in a string, you can use split for create an array of string then use reduce for sum duplicate and last part use Object.entries with indexOf for search the first letter unique. In this example i will add a case that not exist a unique letter.

function findUniqueWord(index) {
  let array = index.split('');  
  let map = array.reduce(function(prev, cur) {
    prev[cur] = (prev[cur] || 0) + 1;
    return prev;
  }, {});
  let finalIndex = null;
  for (const [key, value] of Object.entries(map)) {
    if(value === 1){
      let tempIndex = array.indexOf(key);
      finalIndex = (finalIndex !== null && finalIndex < tempIndex) ? finalIndex : tempIndex;
    }
  }    
  return (finalIndex === null) ? 'No unique letter' : array[finalIndex];
}
console.log(findUniqueWord('Mystery'));
console.log(findUniqueWord('2A2'));
console.log(findUniqueWord('2AA'));
console.log(findUniqueWord('22AA'));

This method is case-sensetive if you don't need it just use toUpperCase() to string before call split method.

Reference:

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

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.