Using the array.filter method to exclude spaces in word count

Published on: June 17, 2019

Before you go any further, I want to mention that the video tutorial below is NOT NEW. I was prompted to do this quick text tutorial because of a very good question asked by someone in the video for the 32nd JavaScript tutorial: How to Count Characters in a Textarea.

In this quick tutorial, I want to show you how to use the array.filter() method in JavaScript using the example of counting characters in a text area without counting the spaces in between. The filter method looks something like this:

array.filter(callback(currentItem, index, arr) {
    //compare code goes here
});

In the above example, the currentItem in the callback is the only required element. The index and array arguments are optional. There's also a fourth item that can be passed but I won't cover that in this tutorial. If the compare code returns true, that the current item will be included in the filter, otherwise it will be excluded. 

For more information, I would recommend checking out the following on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

You can also use an arrow function in the above example. 

What does the code look like that will count the chracters in a string but ignore the spaces? Let's assume that you have an array defined in the variable characters. The variable contains every single character split from a text area:

    characters.filter( item => {
		return (item != ' ');
    }).length;

In the above example, we are applying the filter method to the characters array. This will NOT affect the characters array. The compare funtion returns true if the current item is NOT a space and returns false if it is a space. Through this logic, the spaces are excluded from the next chain, which is asking for the length of the filter. 

For a full example of the code, see the jsfiddle below or go straight there at https://jsfiddle.net/easyjs/bx26nato/

I hope you enjoyed this tutorial! Please feel free to ask questions below or just leave your basic comments. If you think that this requires a brand new video tutorial, let me know!

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:



Comments: