I came across this challenge in which you have to count how many duplicates there are in the string provided.
I came up with this code that is supposed to sort the string if there are duplicates splice them and count them as +1 to the total. If the letter is not a duplicate -> just splice them so I can move forward.
What is going on with the code? I do not want an answer for the challenge but to understand where I went wrong. Why is the code registering the duplicates only if there is 4+ of the same letter?
Here is the code, note that I am only using the var e to see what part of the array is getting spliced.
The expected output:
[[p, p], [a, a, a, a], [c, c, c, c, c, c, c, c], [d, d, d, d], [g, g, g], [e, e]]
If there is 2+ occurrences of the same character slice that chunk of duplicates out and put them in a new array.
function duplicateCount(text) {
const str = Array.from(text.toLowerCase()).sort();
var h = 0;
var e = [];
for (let i = 0; i < str.length; i++) {
if (str.lastIndexOf(str[i]) > 2) {
h++;
e.push(str.splice(0, str.lastIndexOf(str[i]) + 1));
i = 0;
} else {
str.splice(0, 1);
i = 0
}
}
return e
}
console.log(duplicateCount('ppaaaaccccccccgggiyddddhee'));