JavaScript / 4 MIN READ
map() method
Transform array elements with custom functions
From the original Fervor library. Examples may use older package versions.
Let’s Learn the map() method in JavaScript!
It’s probably is one of the most used methods.
map() is a built-in method for arrays in JavaScript that allows you to transform every element of an array, creating a new array with the results.
Here’s the general syntax:
let newArray = oldArray.map(function callback(element, index, array) {
// return transformed element
}[, thisArg]);
In this syntax:
newArrayis the new array that will be created.oldArrayis the original array.callbackis a function that will be run for each element in the array. This function is expected to return the transformed element.elementis the current element that’s being processed.indexis the index of the current element that’s being processed.arrayis the original array.thisArg(optional) is a value to use asthiswhen executingcallback.
Here’s a simple example:
let numbers = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map(function(num) {
return num * num;
});
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
In this example, map() goes through each number in the numbers array and squares it. The result is a new array with the squared numbers.
If you’re familiar with ES6 arrow functions, the code can be made more concise:
let numbers = [1, 2, 3, 4, 5];
let squaredNumbers = numbers.map(num => num * num);
console.log(squaredNumbers); // [1, 4, 9, 16, 25]
Remember that map() does not modify the original array; it returns a new array. This makes map() a pure function, which is a desirable property in functional programming.
Bonus More Examples of using map.
Absolutely, let’s go over some additional examples.
1. Transforming an array of objects:
Let’s say we have an array of objects, where each object represents a person with a name and age. We want to create a new array that contains just the names.
let people = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 25 },
{ name: 'Charlie', age: 30 },
];
let names = people.map(person => person.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']
In this example, map() is used to extract the name property from each object in the array.
2. Converting an array of strings to numbers:
Say we have an array of strings that we want to convert to numbers.
let strings = ['1', '2', '3', '4', '5'];
let numbers = strings.map(Number);
console.log(numbers); // [1, 2, 3, 4, 5]
In this example, the Number function is passed directly to map(), which is allowed because Number is a function that takes a single argument and returns a new value.
3. Index usage with map():
Let’s say we want to create a new array where each element is its own index.
let array = [10, 20, 30, 40, 50];
let indexes = array.map((element, index) => index);
console.log(indexes); // [0, 1, 2, 3, 4]
In this case, we use the index parameter in the map() callback to return the index of each element.
4. Creating an array of JSX elements (in React.js):
In React.js, map() is often used to transform an array of data into an array of JSX elements.
let items = ['Apple', 'Banana', 'Cherry'];
let listItems = items.map((item, index) =>
<li key={index}>{item}</li>
);
// Now you can render `listItems` inside a <ul> element:
/*
<ul>
{listItems}
</ul>
*/
// This would result in:
/*
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>
*/
In this example, each string in the items array is transformed into a <li> element containing that string.
These are just a few examples of what you can do with map(). The real power of map() comes from the fact that you can use any function you want to transform the elements of an array, so the possibilities are virtually endless.
Bonus Arrow Function syntax
Of course! Arrow functions in JavaScript provide a more concise syntax for defining functions, and they can be particularly useful when using methods like map().
Here’s how you can use arrow functions with map():
Example 1: Doubling each number in an array
let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
Example 2: Converting an array of numbers to strings
let numbers = [1, 2, 3, 4, 5];
let strings = numbers.map(num => num.toString());
console.log(strings); // ['1', '2', '3', '4', '5']
Example 3: Adding "Hello " to an array of names
let names = ['John', 'Sarah', 'Alex'];
let greetings = names.map(name => 'Hello ' + name);
console.log(greetings); // ['Hello John', 'Hello Sarah', 'Hello Alex']
In these examples, num => num * 2, num => num.toString(), and name => 'Hello ' + name are all arrow functions. As you can see, they provide a way to define functions with a more succinct syntax. Note that the parentheses around the parameters can be omitted when there’s only one parameter.