Array Functions: forEach, map, and filter
We covered loops in our last section.
Many of the examples we used showed how to loop over arrays of data. However, some built-in functions in JavaScript make looping over and altering arrays even easier.
Three of the most commonly used array methods are forEach
, map
, and filter
. Each of these methods allows you to perform specific actions on the elements of an array, making your code cleaner and more readable.
forEach()
The forEach()
method runs a provided function once for each array element. It's great for tasks where you need to execute some code for every item in an array, like logging values or performing side effects.
Here's an example:
const fruits = ["apple", "banana", "cherry"]; fruits.forEach(function(fruit) { console.log("I love", fruit); });
In this example, forEach()
goes through each item in the fruits
array and logs "I love" followed by the fruit's name. It's a simple way to repeat the same action for each item in the list.
I always like to remind folks that it's easy to adopt these things for strings too. By splitting a string into an array, you can easily manipulate each word or character with one of these functions too:
const sentence = "JavaScript is awesome!"; let words = sentence.split(" "); // Splits the sentence into an array of words words.forEach(function(word, index) { words[index] = word.toUpperCase(); // Convert each word to uppercase }); const newSentence = words.join(" "); // Join the words back into a sentence console.log(newSentence); // Outputs: "JAVASCRIPT IS AWESOME!"
In this example, the split(" ")
method splits the sentence into an array of words. The forEach()
method then iterates over each word, converting it to uppercase. Finally, join(" ")
combines the words back into a single string, showing how we can manipulate and then reconstruct text using these functions.
The forEach()
method is versatile and makes it easy to perform operations on each element in an array or, as shown here, even on parts of a string when split into an array. It's a great tool for tasks where you want to apply the same action to every item.
map()
The map()
method creates a new array by applying a function to each element of the original array.
It's perfect for transforming data without changing the original array:
const numbers = [1, 2, 3, 4]; const squaredNumbers = numbers.map(function(num) { return num * num; }); console.log(squaredNumbers); // Outputs: [1, 4, 9, 16]
In this example, map()
takes each number in the numbers
array, squares it, and returns a new array with the squared numbers.
filter()
The filter()
method creates a new array with all elements that pass a test implemented by a provided function. It's helpful in filtering out unwanted items.
Let's filter out uneven numbers as an example:
let numbers = [1, 2, 3, 4, 5, 6]; let evenNumbers = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evenNumbers); // Outputs: [2, 4, 6]
In this example, filter()
checks each number in the numbers
array and includes it in the new evenNumbers
array if it's even.
Let's do a second example where we will filter out larger words:
const words = ["short", "average", "longer", "lengthiest"]; let longWords = words.filter(function(word) { return word.length > 5; }); console.log(longWords); // Outputs: ["longer", "lengthiest"]
Here, filter()
returns a new array with words over five characters.
And there you have it! There are some really useful built-in functions you can use to loop over and manipulate the arrays you work with without needing to write dynamic loops.
So go ahead, play with them, and see how it can make your JavaScript life easier.
Next up we will look at working with API's.