Member-only story
Creative ways to use Array.map()
2 min readMay 30, 2024
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])…