Reputation: 23
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'));
Upvotes: 1
Views: 989
Reputation: 8162
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:
Upvotes: 1