I know my ‘algorithm’ isn’t useful at all, but I think I encountered a very strange behaviour.
findMatching([“jokes”,”jokeg”],”jokes”); returns jokes. But findMatching([“jokes”,”jokeg”,”jokef”],”jokes”); returns jokes and jokef! When I individually test jokef it does not match.
Here is my code:
for (var p in dataArray) {
if (dataArray[p].length != matching.length) {
dataArray.splice(p,1);
}
}
for (var k = 0; k < matching.length; k++) {
for (var i in dataArray) {
if (dataArray[i].split('')[k] != matching.split('')[k]) {
dataArray.splice(i,1);
}
}
}
if(dataArray.length == 0){
return null;
} else {
return dataArray;
}
Array.splice() is a destructive operation that alters the length of an array. This can clearly be seen if you add a console.log statement to your middle for loop:
The output should look something like this:
It never gets to the ‘f’ in “jokef” because it spliced the array. matching.length is now 2 and the for condition (var k = 0; k < matching.length; k++) is now false, causing the loop to break and the JavaScript engine to move onto the next block.