I need help on filtering a Javascript array to remove names that DO NOT include at least one of a series of letters listed in a second array. I have tried over and over, using combinations of filter(), and also nested FOR loops. EXAMPLE:
name = ["chuck","lina","wanda","denise","reggie","candy"];
letter = ["h","l","z","e"];
The array returned by filter() should be:
nametwo = ["wanda","candy"];
It's simple to explain but I just cannot make it work in code. I've found many examples of filter() on here but none has helped. Thanks!
CodePudding user response:
Basically the same question here
const name = ["chuck","lina","wanda","denise","reggie","candy"];
const letter = ["h","l","z","e"];
const checker = value =>
!letter.some(element => value.includes(element));
console.log(name.filter(checker));
CodePudding user response:
For searching letters inside a string, you should use indexOf function.
If you want one line solution you can do it this way:
const names = ["chuck","lina","wanda","denise","reggie","candy"];
const letters = ["h","l","z","e"];
const result = names.filter(name => letters.filter(letter => name.indexOf(letter) !== -1).length === 0);
console.log(result)
And you can do it use two cycles:
const names = ["chuck","lina","wanda","denise","reggie","candy"];
const letters = ["h","l","z","e"];
const result = [];
for (let i = 0; i < names.length; i ) {
let isContainLetter = false;
for (let j = 0; j < letters.length; j ) {
if (names[i].indexOf(letters[j]) !== -1) {
isContainLetter = true;
break;
}
}
if (!isContainLetter) result.push(names[i]);
}
console.log(result)
CodePudding user response:
You could filter with every
and check if the name does not contains letters.
const
names = ["chuck", "lina", "wanda", "denise", "reggie", "candy"],
letters = ["h", "l", "z", "e"],
result = names.filter(n => letters.every(l => !n.includes(l)));
console.log(result); // ["wanda", "candy"]