How to filter only 4 letter words from array in JavaScript

← PrevNext →

To filter words or elements from an array in JavaScript, you can use the array.filter() method. For example, if you have an array containing string values or words, and you want to extract only the 4-letter words, the array.filter() method makes it easy.

How to filter only 4 letter words from array - 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.

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>
Try it

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.

← PreviousNext →