I'm trying to solve a coderbyte challenge in which I have to compare letters in each word in a string and return the word with the most duplicated letters. EX: "Hello World" -> "Hello"
I'm still trying to solve the problem but I ran into some bizarre behavior involving Array.prototype.pop();
Here is my code:
function LetterCountI(str) {
str = str.split(" ");
var largest = "";
var letterCount = 0;
for (var i = 0; i <str.length;i++) {
letterCount = findMatches(str[i].split(""));
}
function findMatches(array) {
var letterCount = 0;
while (array.length) {
var letter = array.pop();
var counter = 0;
var arrayCopy = array;
letterCount += compareRecursive(letter, arrayCopy, counter);
}
return letterCount;
}
function compareRecursive(letter, a, counter) {
if (a.length === 0) {
return counter;
}
var n = a.pop();
if (letter === n) {
counter++;
}
return compareRecursive(letter, a, counter);
}
return letterCount;
}
What is happening is I am using Array.prototype.pop() in my compareRecursive function to return the last index of the array and to make the array smaller so I could loop through the whole string. I call compareRecursive in my findMatches function. After I call compareRecursive the array variable and the arrayCopy variables get emptied. From my understanding of scope the compareRecursive function should have its own copy of the array since I'm passing it in as a parameter, why is Array.prototype.pop() affecting the array and arrayCopy variables in my findMatches function?
When I change the line
var n = a.pop();
To:
var n = a[0];
a = a.slice(1);
The array and arrayCopy variables in the findMatches functions aren't affected. Why is this?