Creative ways to use Array.map()

aneeqakhan

Aneeqa Khan

Posted on May 31, 2024

Creative ways to use Array.map()

Hello fellow developers!

Have you ever wondered about the various ways to use the array.map() function to achieve different transformations?

I have compiled a list of ideas on how to utilize them effectively map() function.

1. Basic Transformation

Transform each element in an array.

const numbers = [1, 2, 3];
const squares = numbers.map(x => x * x);
console.log(squares); // [1, 4, 9]
Enter fullscreen mode Exit fullscreen mode

2. Mapping to Objects

Transform an array of values to an array of objects.

const names = ['Alice', 'Bob', 'Charlie'];
const people = names.map(name => ({ name }));
console.log(people); // [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }]
Enter fullscreen mode Exit fullscreen mode

3. Extracting Properties

Extract a specific property from an array of objects.

const users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
];
const ids = users.map(user => user.id);
console.log(ids); // [1, 2]
Enter fullscreen mode Exit fullscreen mode

4. Changing Array of Arrays

Transform an array of arrays.

const pairs = [[1, 2], [3, 4], [5, 6]];
const summedPairs = pairs.map(pair => pair[0] + pair[1]);
console.log(summedPairs); // [3, 7, 11]
Enter fullscreen mode Exit fullscreen mode

5. Asynchronous Operations

Handle asynchronous operations within map (commonly using Promise.all).

const fetchData = async id => {
    // Simulate an async operation
    return new Promise(resolve => setTimeout(() => resolve(`Data for ID ${id}`), 1000));
};

const ids = [1, 2, 3];
const promises = ids.map(id => fetchData(id));

Promise.all(promises).then(data => console.log(data)); // ["Data for ID 1", "Data for ID 2", "Data for ID 3"]
Enter fullscreen mode Exit fullscreen mode

6. Conditional Mapping

Apply a transformation conditionally.

const numbers = [1, 2, 3, 4, 5];
const evensDoubled = numbers.map(num => num % 2 === 0 ? num * 2 : num);
console.log(evensDoubled); // [1, 4, 3, 8, 5]
Enter fullscreen mode Exit fullscreen mode

7. Spreading Arrays into Function Arguments

You can use map to spread array elements as arguments to a function.

const numbers = [[1, 2], [3, 4], [5, 6]];

// Creating an array of sums
const sums = numbers.map(([a, b]) => a + b);
console.log(sums); // [3, 7, 11]
Enter fullscreen mode Exit fullscreen mode

8. Zipping Arrays

Combine two arrays into an array of pairs.

const keys = ['name', 'age'];
const values = ['Alice', 25];

const zipped = keys.map((key, i) => [key, values[i]]);
console.log(zipped); // [["name", "Alice"], ["age", 25]]
Enter fullscreen mode Exit fullscreen mode

9. Mapping with Index

Utilizing the index parameter in JavaScript’s map function allows you to include the position of each element in your transformations.

const colors = ['red', 'green', 'blue'];
const colorDescriptions = colors.map((color, index) => `Color ${index + 1}: ${color}`);
console.log(colorDescriptions); // ['Color 1: red', 'Color 2: green', 'Color 3: blue']
Enter fullscreen mode Exit fullscreen mode

10. Flattening an Array

Using map to flatten a 2D array, though flatMap is better suited for this task.

const nestedArray = [[1, 2], [3, 4], [5, 6]];
const flattenedArray = nestedArray.map(subArray => subArray).flat();
console.log(flattenedArray); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Thank you for reading! Feel free to connect with me on LinkedIn or GitHub.

💖 💪 🙅 🚩
aneeqakhan
Aneeqa Khan

Posted on May 31, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Math Object Cheatsheet
javascript JavaScript Math Object Cheatsheet

November 25, 2024

Human-Readable JavaScript
javascript Human-Readable JavaScript

November 20, 2024

CyroScript Weekly Digest: Nov 15, 2024
javascript CyroScript Weekly Digest: Nov 15, 2024

November 16, 2024