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>
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>
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.