
The JavaScript map() Method

It feels like a very long time since I wrote about JavaScript's filter() method, so in the interest of completeness, I'm looping back to cover two other array manipulation methods: reduce(), and map(). Today, it's the turn of map() which ‑ although simple at its core ‑ is an extremely powerful thing to have in your toolbox.
Understanding map()
At its heart, JavaScript's map() method transforms an array. It takes each element, applies the callback function you've provided to the element, and then assembles that output into a new array.
Fundamentals
The map() function is part of the Array prototype (Array.prototype.map()), making it available for any array. It requires a callback function as its argument, which is then executed on every element within the array. The return from this callback function is then used to construct the new array, element by element.
Syntax
Here's what the syntax looks like:
const newArray = array.map(function(currentValue, index, arr), thisValue);This breaks down as follows:
currentValue: The current element being processed in the array;index(optional): The index of the current element being processed;arr(optional): The array map was called upon;thisValue(optional): A value to use as this when executing the callback.
A Simple Example
As a very basic example, imagine that you have an array of numbers, and that you need to find the square of each. Here's how map() could be used:
const numbers = [1, 2, 3, 4, 5];const squaredNumbers = numbers.map((number) => number * number);console.log(squaredNumbers);//=> [1, 4, 9, 16, 25]Essentially, map() loops over each item within the numbers array, multiplies it by itself, and then includes that result in squaredNumbers.
A More Complex Example
For a slightly more complicated example, imagine that you'd dealing with a set of products where you need to apply a 10% discount to the price of each. We can use map() to loop over each product within an array, retain all the other fields (using the ... spread syntax), and multiply the price field by 0.9:
const products = [ { name: 'MacBook', price: 2000 }, { name: 'iPhone', price: 750 }, { name: 'iPad', price: 1200 },];const discountedProducts = products.map((product) => ({ ...product, price: product.price * 0.9,}));console.log(discountedProducts);/* Output: [ { name: 'MacBook', price: 1800, }, { name: 'iPhone', price: 675, }, { name: 'iPad', price: 1080, }, ];*/Looping over data in JSX with map()
If you've spent any time developing in React, you will no doubt already be familiar with (or at least have come across) the practice of using map() within JSX to render out lists of elements. It's an elegant application of map() which perhaps falls outside of the more conventional uses I've discussed until now, so it deserves a discussion here...
Why Use map() in JSX?
React is declarative and encourages declarative programming where you describe what the UI should look like for given states rather than detailing the steps to achieve it (which would be 'imperative programming'). Using map() to loop over a dataset and define the output for each aligns very neatly with this declarative philosophy, allowing us as developers to transform arrays of data into arrays of components.
How It Works
In JSX, we can use map() to iterate over an array of data, and return a new array of React elements or components. Each is then rendered into the UI. It's a pattern that is particularly useful for lists, tables, or any collection of similar elements derived from an array. It's how I populate a lot of the different aspects of my own personal website here. For example, the Article Listing pages, the Project Listing page, and even the categories and related articles that are listed at the bottom of this page.
An Example
Imagine you have a list of clients in an array that you want to display in a simple ordered list:
const clients = ['IMG Licensing', 'Apple', 'Virgin Atlantic', 'BBC', 'Cisco'];To output these into a list in React would look like this:
const ClientsList = ({ clients }: { clients: string[] }) => ( <ul> {clients.map((client, i) => ( <li key={i}>{client}</li> ))} </ul>);It's as simple as that. The only real thing to bear in mind is that when you're rendering a list of elements based on a dataset like this, React requires a unique key prop for each element. This allows React to identify which elements have changed, added, removed without having to force a complete repaint.
For the sake if this example, I'm using the index (i), but this should be done with caution; you would normally find something more unique within the data itself to populate each key.
Tips for using map()
Transformation Power
map() is all about the transformation of data. This is likely the method you need when you need to convert data from one form to another.
Chainability
Much like filter(), map() can be chained with other array methods, such as filter(), or reduce(), to perform more complex data transformations.
Performance Considerations
It's important to bear in mind that map() will process every element within the array. For larger arrays, you should consider the performance implications of the transformation you're applying. It might be that it makes sense to filter the dataset before mapping.
The Wrap‑Up
When it comes to transforming data from one structure to another, map() is very likely to be the tool you're after.
Categories:
Related Articles

Angular Standalone Components: Do We Still Need Modules? 
Declarative vs. Imperative Programming. Declarative vs. Imperative Programming

Reduce() in JavaScript. reduce()in JavaScript
Using the filter() Method in JavaScript. Using the
filter()Method in JavaScript
Using Vue's Teleport for Modals and Portals. Using Vue's Teleport for Modals and Portals

Integrating CMSes with HTML, CSS, and JavaScript. Integrating CMSes with HTML, CSS, and JavaScript

The Longest Palindromic Substring in JavaScript. The Longest Palindromic Substring in JavaScript

Installing Gatsby onto an M1 MacBook Air. Installing Gatsby onto an M1 MacBook Air

Optimising Performance in React with useMemo and useCallback. Optimising Performance in React with
useMemoanduseCallback
Invoked Function Expressions (IIFE). Invoked Function Expressions (IIFE)

Graph Traversal: Solving the 'Course Schedule' Problem. Graph Traversal: Solving the 'Course Schedule' Problem

CSS box‑sizing: Controlling the Element Box Model. CSS
box‑sizing: Controlling the Element Box Model