I want to show only those which have two 'a'.
Based on your requirement, the number of char a in Banana equals 3. So it shouldn't be shown. Let's try to filter p char instead.
return countChar(charArray, char) == 2; // Adjust condition here
From the above condition, you can adjust as you wish, For example:
> 1 // when you want to filter string having greater than 1 char
or
>= 2 // when you want to filter string having greater or euqal 2 char
const fruits = ['Apple', 'Apricots', 'Banana', 'Watermelon', 'Strawberry', 'Peech'];
const countChar = (charArray, char) => charArray.reduce((acc, curr) => (acc = acc + (curr == char ? 1 : 0), acc), 0);
let filteredFruits = (char) => fruits.filter(fruit => {
const charArray = fruit.toLowerCase().split('');
return countChar(charArray, char) == 2; // Adjust condition here
})
console.log(filteredFruits('a'));
console.log(filteredFruits('p'));
Bonus
In your code, it's missing return keyword. You can resolve by 2 ways:
return keyword
{
return fruit.toLowerCase().includes('a');
})
- shorthand, no need bracket
{}
=> fruit.toLowerCase().includes('a');