Blog Datasheets Home About me Clients My work Services Contact

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:

1
2
let a = [1, 2, 3, 4, 5, 6];
let b = [];

The old-school way to populate b with the squares of a’s values might be using a for loop:

1
2
3
4
5
for (let i = 0; i < a.length; i++) {
    b.push(a[i] * a[i]);
}

// Now b = [1, 4, 9, 16, 25, 36];

While this method works, it has several drawbacks:

Mapping with map()

A more modern and concise approach is to use the map() method:

1
b = a.map((el) => el * el);

With map():

But what if you need the index? The map() method provides it for you:

1
2
3
4
b = a.map((el, index) => {
    console.log(`Index: ${index}, Value: ${el}`);
    return el * el;
});

Here’s what happens:

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:

1
2
3
4
5
6
7
// Mapping and transforming each element to its square root
let sqrtArray = a.map(Math.sqrt);
// sqrtArray = [1, 1.4142135623730951, 1.7320508075688772, 2, 2.23606797749979, 2.449489742783178]

// Mapping using both the element and its index
let indexedSquares = a.map((el, index) => `${index}: ${el * el}`);
// indexedSquares = ["0: 1", "1: 4", "2: 9", "3: 16", "4: 25", "5: 36"]

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:

1
2
3
let evenNumbers = a.filter((el) => el % 2 === 0);
console.log(evenNumbers);
// evenNumbers = [2, 4, 6]

Extending Our Filtering Example

Here are more ways you can use filter():

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Filter out all odd numbers
let oddNumbers = a.filter((el) => el % 2 !== 0);
// oddNumbers = [1, 3, 5]

// Filter and keep numbers greater than 3
let numbersGreaterThanThree = a.filter((el) => el > 3);
// numbersGreaterThanThree = [4, 5, 6]

// Filter based on more complex conditions, like prime numbers (simple example)
let primeNumbers = a.filter((num) => {
    for (let i = 2; i < num; i++)
        if (num % i === 0) return false;
    return num > 1;
});
// primeNumbers = [2, 3, 5]

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!


➡️ Open/Close principle


⬅️ Leveraging SOLID principles in modern web application development


Go back to Posts.