How to to use filter() with RegExp object to search patterns in array

← PrevNext →

Let us assume, I have an array and I want to search for strings or values using a pattern or a character or a group of characters. There are many ways you can do this. However, here I am going to show you how to use the .filter() method with RegExp object to filter values from array using patterns.

I've shared two examples here.

But first, lets see the syntax.

filter() method syntax

filter (callback_function, thisValue)

callback_function: A function to run for each array value (or element).

theValue: The value passed to the callback function.

RegExp object syntax

RegExp (pattern, modifiers)

Examples.

🚀 Example 1

In this example, I have three elements. All are string elements. I want to filter out elements that has the characters "ag". I don't care if the characters are in upper case or lower case.

<script>
  const arrBirds = ["Mourning Dove", "Bald Eagle", 'Eurasian Collared-Dove'];
  // Create a regex object (a constructor).
  let regex = new RegExp('ag', 'i'); 	    // get elements (values) that has "ag".

  // Tests for a match.
  let filtered = arrBirds.filter(item => regex.test(item));
  console.log(filtered);		// Output: Bald Eagle
</script>
Try it

First I have declared a constructor of RegExp.

The RegExp has two arguments.

1) The pattern to search. It will filter values (or elements) that has the characters "ag".

2) The modifier "i": The "i" modifier performs a case-insensitive matching. So it doesn't matter if the characters are in upper case or lower case.

The .filter() method creates a new array from arrBirds(), only after filtering out elements that match the pattern I have provided to the RegExp.

The regex uses the test() method (regex.test(item)) to test for a match in the element. If it finds a match, it will "true", else "false".

🚀 Example 2

I have an array of numbers and string values. I want to filter out only the number elements using filter() and RegExp object.

<script>
  const arr1 = [350, 'north', 99, 'south'];
  let regex = new RegExp(/^\d+$/);          // get only numeric values.
  let filtered = arr1.filter(v => regex.test(v));
  console.log(filtered);		// Output: [350,99]
</script>
Try it

Note: It will not filter -ve (negative) numbers.

Now lets do the opposite. We will filter out elements that have "alphabets" only.

<script>
  const arr1 = [350, 'north', 99, 'south'];
  let regex = new RegExp(/^\D+$/);          // get only alphabets values.
  let filtered = arr1.filter(v => regex.test(v));
  console.log(filtered);		// Output: [north,south]
</script>
Try it

Happy coding. 🙂

← PreviousNext →