Member-only story

Creative ways to use Array.map()

Aneeqa Khan
2 min readMay 30, 2024
cover image with green field background and written 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]

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' }]

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]

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])…

--

--

Aneeqa Khan
Aneeqa Khan

Written by Aneeqa Khan

I’m a frontend web and mobile developer specialized in web/mobile designs and frontend frameworks. I usually work with React, React Native, Next and TypeScript.

No responses yet