I have an array of strings and I am attempting to filter the array of strings that contain repeating letters. However, two weird things are happening that I don't understand. Here is my code:
var array = ["aba", "aab", "baa"];
var pattern = /(\D)\1+/gi;
var filteredArr = array.filter(function(element){
console.log(element);
console.log(pattern.test(element));
return pattern.test(element) != true;
});
console.log(filteredArr);
Some weird things happen. Within the filter function, I test if the regular expression is true or false and that goes as it should.
pattern.test("aba") = false;
pattern.test("aab") = true;
pattern.test("baa") = true;
However, if I test them outside of the function, "baa" seems to return false...which is weird right?
console.log(pattern.test("aba")); //returns false
console.log(pattern.test("aab")); //returns true
console.log(pattern.test("baa")); //returns false
Onto the next weird thing. The filter function SHOULD return the elements that do NOT pass (ie return false) the filter test. My expected output would be:
filteredArr = ["aba"];
However, with the way the code is, my output is:
filteredArr = ["aba", "aab", "baa"];
What's even more strange is that if I change the filter function to return the elements that DO pass (ie return true) the test, the expected output would be:
filteredArr = ["aab", "baa"];
However, the output that I receive is an empty array:
filteredArr = [];
I'm super confused. Is my regular expression wrong or am I perhaps attempting something that the filter function isn't able to do? Here is a fiddle with all of the code: