Question Is is possible, to match a word that contains the same character in different positions of string array?
for example:- suppose i have the following array
arr1=["apply","application","apple","alphabet","killo","pipe"]
Now I want the following output of the element that have double 'p' (may be together or different position)
Desirable output:
arr1=["apply","application","apple","pipe"]
if i put 'l' then I should get output arr1=[killo] output
arr1=["apply","application","apple","alphabet","killo","pipe"]
ans= arr1.filter(x => x.includes('p'))
console.log(ans)
but i am getting following output
arr1=["apply","application","apple","alphabet","pipe"]
You can use the following regex format:
var arr1 = ["apply", "application", "apple", "alphabet", "killo", "pipe"];
function filter_dup(arr, c) {
return arr.filter(x => x.match(new RegExp(`.*${c}.*${c}.*`)));
}
console.log(filter_dup(arr1, 'p'));
console.log(filter_dup(arr1, 'l'));
You can also use String.prototype.indexOf and String.prototype.lastIndexOf (if the first and last indices of a character are different than there are at least two occurrences of that character):
var arr1 = ["apply", "application", "apple", "alphabet", "killo", "pipe"];
function filter_dup(arr, c) {
return arr.filter(x => x.indexOf(c) != x.lastIndexOf(c));
}
console.log(filter_dup(arr1, 'p'));
console.log(filter_dup(arr1, 'l'));