0

How can I filter 2 characters from the array string?

For example, I want to show only those which have two 'a'.

The result will be 'Banana' instead of 'a' in every string

const fruits = ['Apple', 'Apricots', 'Banana', 'Watermelon', 'Strawberry', 'Peech'];

let filteredFruits = fruits.filter(fruit => {
  fruit.toLowerCase().includes('a');

})

console.log(filteredFruits);

1
  • At first you need to return inside the filter function to get a result. So (fruit => { return .... }) play around with this. Commented Apr 28, 2021 at 10:01

2 Answers 2

1

You could take a regular expression which searches fro a letter and take the length if not null.

const
    fruits = ['Apple', 'Apricots', 'Banana', 'Watermelon', 'Strawberry', 'Peech'],
    filteredFruits = fruits.filter(fruit => fruit.match(/a/gi)?.length > 1)

console.log(filteredFruits);

Sign up to request clarification or add additional context in comments.

Comments

0

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:

  1. return keyword
    {
      return fruit.toLowerCase().includes('a');
  
    })
  1. shorthand, no need bracket {}
 => fruit.toLowerCase().includes('a');

1 Comment

Does this answer your question? Let me know if you need any help ^^! @fahad javed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.