As JavaScript developers, we often find ourselves looping over arrays to transform data. Methods like forEach, map, filter and reduce can make this process cleaner and more maintainable. In this article, we’ll look at how these methods work and when to use each one.
The Basics The map, filter and reduce methods provide simple ways to iterate over an array without needing to set up a traditional for or while loop.
- Map: Transforms each element in an array, returning a new array with the transformed data
- Filter: Returns a subset of the array, filtering out elements that don’t pass a test
- Reduce: Iterates through an array, returning a single value
Simplifying Loops
Let’s look at a simple example. Say we have an array of numbers and want to double each number. With a normal for loop, we would write:
const numbers = [1, 2, 3, 4];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
doubled.push(numbers[i] * 2);
}
// doubled = [2, 4, 6, 8]