How to filter only 4 letter words from array in JavaScript

← PrevNext →

Let us assume I have an array in JavaScript with some string values or words. I want to extract or filter only 4 letter words from the array.

How to filter only 4 letter words from array - JavaScript

Here’s an array for example.

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 letters words?

Anybody can tell by just looking at the above array. What if it has a long list of words?

hmm… no problem.

The array.filter() method makes it easy.

  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>');

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

That’s it. 🙂

← PreviousNext →