G2Labs Grzegorz Grzęda
JavaScript Array Transformation: Map and Filter
May 30, 2023
JavaScript Array Transformation: Map and Filter
In JavaScript, when we’re juggling arrays of objects or any kind of data, we often find ourselves needing to transform this data in some way. Let’s delve into two powerful array methods that can help us manipulate array data efficiently: map
and filter
.
Starting Point
Imagine you have an array a
filled with numbers and you wish to create a new array b
that will hold the squares of these numbers. Initially, our arrays look like this:
The old-school way to populate b
with the squares of a
’s values might be using a for
loop:
While this method works, it has several drawbacks:
- The
for
loop notation is verbose. - Managing the index
i
can lead to mistakes. - The loop is stateful, meaning the index
i
changes state with each iteration.
Mapping with map()
A more modern and concise approach is to use the map()
method:
|
|
With map()
:
- The code is shorter and cleaner.
- There is no need for manual indexing.
- The operation is less stateful; we aren’t manually changing the state of
b
.
But what if you need the index? The map()
method provides it for you:
Here’s what happens:
map()
takes a callback function that acts on each element.currentValue
: the current element being processed.index
(optional): the index of the current element.array
(optional): the arraymap
was called upon.thisValue
(optional): a value to use asthis
when executing the callback.
Remember, map()
returns a new array with the results of the callback function.
Extending Our Mapping Example
Let’s extend our mapping example to cover some corner cases and provide more examples:
|
|
Filtering with filter()
While map()
is great for transforming data, filter()
is your tool for selecting specific elements that meet certain criteria.
The filter()
method works similarly to map()
but expects a boolean return value from the function to decide if the element should be included in the new array.
Let’s filter out even numbers from array a
:
Extending Our Filtering Example
Here are more ways you can use filter()
:
|
|
Both map()
and filter()
are non-mutating methods—they do not change the original array. Instead, they return a new array, making your code cleaner and more functional.
Conclusion
JavaScript provides these utility methods to work with arrays in a concise and less error-prone way. As a beginner programmer, mastering map()
and filter()
will not only help you write less code but also enable you to write more readable and maintainable code. Happy coding!