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.
Example:
Let us assume, this is the array.
let arr = ['able', 'ache', 'actor', 'zenic', 'zone'];
It has five different words and just three are 4 letter words. How do I extract only 4 letter words from the array.
The array.filter() method makes it easy.
<script> let just4_Letters = () => { let arr = ['able', 'ache', 'actor', 'zenic', 'zone']; let theWords = arr.filter(words => words.length === 4); document.write('4 letter words: <b>' + theWords + '</b>'); } just4_Letters(); </script>
In fact, its super easy and a one-liner solution.
The .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.
Using this method you can filter even and odd numbers from an array or simply filter out only numbers from an array of alpha-numeric values etc.