Reputation: 83
I'm doing some exercises. the question is to find the first none-repeated character in a string. My idea is: turn string to array. assign array[0] to a new variable, and remove this array[0] from array. Check if this new array contain this variable, if not, return this variable. Else, use filter to remove same value elements and get a new array. repeat the process. the code as following.
const NoneReChar = (str) => {
let tempArr = str.split('');
let start = tempArr[0];
while (true) {
tempArr.shift();
if (!tempArr.includes(start)) {
return start;
} else {
tempArr.filter(char => char !== start);
start = tempArr[0];
}
}
}
console.log(NoneReChar("aaaabbbeccc"))
I was expect output 'e', but I keep getting 'a'...where are the mistakes I made here?
Upvotes: 3
Views: 170
Reputation: 100
const NoneReChar = (str) => {
const tempArr = str.split('');
let result = 'Not Found';
for (let index = 0; index < tempArr.length; index++) {
const firstIndex = tempArr.indexOf(tempArr[index]);
const lastIndex = tempArr.lastIndexOf(tempArr[index]);
if (firstIndex === lastIndex) {
result = tempArr[index];
break;
}
}
return result;
}
console.log(NoneReChar("aaaabbbeccc"));
Upvotes: 0
Reputation: 192317
The Array.filter()
method doesn't mutate the original array. You need to assign the result of filter to tempArr
:
tempArr = tempArr.filter(char => char !== start);
Example:
const NoneReChar = (str) => {
let tempArr = str.split('');
let start = tempArr[0];
while (true) {
tempArr.shift();
if (!tempArr.includes(start)) {
return start;
} else {
tempArr = tempArr.filter(char => char !== start);
start = tempArr[0];
}
}
}
console.log(NoneReChar("aaaabbbeccc"))
However, you don't handle the not found case. To handle it instead of true
, the while clause should stop when the array is empty:
const NoneReChar = (str) => {
let tempArr = str.split('');
let start = tempArr[0];
while (tempArr.length) {
tempArr.shift();
if (!tempArr.includes(start)) {
return start;
} else {
tempArr = tempArr.filter(char => char !== start);
start = tempArr[0];
}
}
return null;
}
console.log(NoneReChar("aabbcc"))
Another option is comparing the length of the array before and after filtering. If the length is the same, the item was not repeated:
const NoneReChar = (str) => {
let tempArr = str.split('');
while (tempArr.length) {
const [start, ...rest] = tempArr; // take the 1st item and the rest
tempArr = rest.filter(char => char !== start); // filter out start
if(tempArr.length === rest.length) { // check current and previous arrays, and if the length still matches, start didn't appear again
return start;
}
}
return null;
}
console.log(NoneReChar("aabzbcc"))
Upvotes: 6