How to use filter() to find words in an array that starts with a letter?

← Prev

In this article, I am sharing two different methods to use the filter() method in JavaScript to extract words from an array that start with a specific letter. These methods include using the startsWith() method and RegExp (regular expressions) object. While these are effective techniques, there may be other methods available to achieve the same result.

use filter() method with startsWith() method in JavaScript

Syntax array.filter()

array.filter(callback_function, thisValue)

1) callback_function: A function to execute for each element. The callback function will look like this... function(currentValue, index, arr).

2) thisValue: A value as this passed to the callback function.

The array.filter() method returns a new array of items. These items pass through a test function or a condition. If the condition is true, then the item is added in the new array.

Example 1: Using filter() with startsWith() method

<script>
  let filter_words = () => {
    const arr = ["paper", "eraser", 'ruller', 'pen', 'pencil'];

    let filtered = arr.filter (arr => arr.startsWith('p')); // words that start with "p"
    document.getElementById("result").innerHTML = '<b>Result</b> - ' + filtered;
  }
  // Result - paper,pen,pencil

  filter_words();
</script>
Try it

Example 2: Using filter() with RegExp Object

You can also use Regular expression and get the same result. I am using the RegExp object to filter words using a pattern.

<script>
  let filter_words = () => {
    const arr = ["paper", "eraser", 'ruller', 'pen', 'pencil'];

    // Create a regex object (a constructor).
    let regex = new RegExp('p', 'i');    // find words that start with 'p'. the 'i' is for case-insensitive matching
    let filtered = arr.filter(item => regex.test(item)); // Tests for a match.

    document.getElementById("result").innerHTML = filtered;
  }
  // Result - paper,pen,pencil

  filter_words();
</script>
Try it

The test() method of the RegExp object, returns a boolean true or false. True, if it finds a match or if a pattern is found.

← Previous