Javascript array map function

JavaScript Array map()

Return a new array with the square root of all element values:

Multiply all the values in an array with 10:

const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) return num * 10;
>

Description

map() creates a new array from calling a function for every array element.

map() does not execute the function for empty elements.

map() does not change the original array.

See Also:

Syntax

Parameters

Parameter Description
function() Required.
A function to be run for each array element.
currentValue Required.
The value of the current element.
index Optional.
The index of the current element.
arr Optional.
The array of the current element.
thisValue Optional.
Default value undefined .
A value passed to the function to be used as its this value.

Return Value

More Examples

Get the full name for each person:

function getFullName(item) return [item.firstname,item.lastname].join(» «);
>

Browser Support

map() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Array.prototype.map()

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

Try it

Syntax

map(callbackFn) map(callbackFn, thisArg) 

Parameters

A function to execute for each element in the array. Its return value is added as a single element in the new array. The function is called with the following arguments:

The current element being processed in the array.

The index of the current element being processed in the array.

The array map() was called upon.

A value to use as this when executing callbackFn . See iterative methods.

Return value

A new array with each element being the result of the callback function.

Description

The map() method is an iterative method. It calls a provided callbackFn function once for each element in an array and constructs a new array from the results.

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

The map() method is a copying method. It does not alter this . However, the function provided as callbackFn can mutate the array. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:

  • callbackFn will not visit any elements added beyond the array’s initial length when the call to map() began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are not visited.

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The map() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Since map builds a new array, calling it without using the returned array is an anti-pattern; use forEach or for. of instead.

Examples

Mapping an array of numbers to an array of square roots

The following code takes an array of numbers and creates a new array containing the square roots of the numbers in the first array.

const numbers = [1, 4, 9]; const roots = numbers.map((num) => Math.sqrt(num)); // roots is now [1, 2, 3] // numbers is still [1, 4, 9] 

Using map to reformat objects in an array

The following code takes an array of objects and creates a new array containing the newly reformatted objects.

const kvArray = [  key: 1, value: 10 >,  key: 2, value: 20 >,  key: 3, value: 30 >, ]; const reformattedArray = kvArray.map(( key, value >) => ( [key]: value >)); console.log(reformattedArray); // [< 1: 10 >, < 2: 20 >, < 3: 30 >] console.log(kvArray); // [ // < key: 1, value: 10 >, // < key: 2, value: 20 >, // // ] 

Mapping an array of numbers using a function containing an argument

The following code shows how map works when a function requiring one argument is used with it. The argument will automatically be assigned from each element of the array as map loops through the original array.

const numbers = [1, 4, 9]; const doubles = numbers.map((num) => num * 2); console.log(doubles); // [2, 8, 18] console.log(numbers); // [1, 4, 9] 

Calling map() on non-array objects

The map() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

const arrayLike =  length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by map() since length is 3 >; console.log(Array.prototype.map.call(arrayLike, (x) => x ** 2)); // [ 4, 9, 16 ] 

Using map() generically on a NodeList

This example shows how to iterate through a collection of objects collected by querySelectorAll . This is because querySelectorAll returns a NodeList (which is a collection of objects).

In this case, we return all the selected option s’ values on the screen:

const elems = document.querySelectorAll("select option:checked"); const values = Array.prototype.map.call(elems, ( value >) => value); 

An easier way would be the Array.from() method.

Using map() on sparse arrays

A sparse array remains sparse after map() . The indices of empty slots are still empty in the returned array, and the callback function won’t be called on them.

.log( [1, , 3].map((x, index) =>  console.log(`Visit $index>`); return x * 2; >), ); // Visit 0 // Visit 2 // [2, empty, 6] 

Using parseInt() with map()

It is common to use the callback with one argument (the element being traversed). Certain functions are also commonly used with one argument, even though they take additional optional arguments. These habits may lead to confusing behaviors.

While one might expect [1, 2, 3] , the actual result is [1, NaN, NaN] .

parseInt is often used with one argument, but takes two. The first is an expression and the second is the radix to the callback function, Array.prototype.map passes 3 arguments:

The third argument is ignored by parseInt —but not the second one! This is the source of possible confusion.

Here is a concise example of the iteration steps:

// parseInt(string, radix) -> map(parseInt(value, index)) /* first iteration (index is 0): */ parseInt("1", 0); // 1 /* second iteration (index is 1): */ parseInt("2", 1); // NaN /* third iteration (index is 2): */ parseInt("3", 2); // NaN 

Then let’s talk about solutions.

const returnInt = (element) => parseInt(element, 10); ["1", "2", "3"].map(returnInt); // [1, 2, 3] // Actual result is an array of numbers (as expected) // Same as above, but using the concise arrow function syntax ["1", "2", "3"].map((str) => parseInt(str)); // [1, 2, 3] // A simpler way to achieve the above, while avoiding the "gotcha": ["1", "2", "3"].map(Number); // [1, 2, 3] // But unlike parseInt(), Number() will also return a float or (resolved) exponential notation: ["1.1", "2.2e2", "3e300"].map(Number); // [1.1, 220, 3e+300] // For comparison, if we use parseInt() on the array above: ["1.1", "2.2e2", "3e300"].map((str) => parseInt(str)); // [1, 2, 3] 

One alternative output of the map method being called with parseInt as a parameter runs as follows:

const strings = ["10", "10", "10"]; const numbers = strings.map(parseInt); console.log(numbers); // Actual result of [10, NaN, 2] may be unexpected based on the above description. 

Mapped array contains undefined

When undefined or nothing is returned:

const numbers = [1, 2, 3, 4]; const filteredNumbers = numbers.map((num, index) =>  if (index  3)  return num; > >); // index goes from 0, so the filterNumbers are 1,2,3 and undefined. // filteredNumbers is [1, 2, 3, undefined] // numbers is still [1, 2, 3, 4] 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

JavaScript Map – How to Use the JS .map() Function (Array Method)

Nathan Sebhastian

Nathan Sebhastian

JavaScript Map – How to Use the JS .map() Function (Array Method)

Sometimes you may need to take an array and apply some procedure to its elements so that you get a new array with modified elements.

Instead of manually iterating over the array using a loop, you can simply use the built-in Array.map() method.

Here’s an Interactive Scrim of How to Use the JS .map() Function

The Array.map() method allows you to iterate over an array and modify its elements using a callback function. The callback function will then be executed on each of the array’s elements.

For example, suppose you have the following array element:

Now imagine you are required to multiply each of the array’s elements by 3 . You might consider using a for loop as follows:

let arr = [3, 4, 5, 6]; for (let i = 0; i < arr.length; i++)< arr[i] = arr[i] * 3; >console.log(arr); // [9, 12, 15, 18]

But you can actually use the Array.map() method to achieve the same result. Here’s an example:

let arr = [3, 4, 5, 6]; let modifiedArr = arr.map(function(element)< return element *3; >); console.log(modifiedArr); // [9, 12, 15, 18]

The Array.map() method is commonly used to apply some changes to the elements, whether multiplying by a specific number as in the code above, or doing any other operations that you might require for your application.

How to use map() over an array of objects

For example, you may have an array of objects that stores firstName and lastName values of your friends as follows:

You can use the map() method to iterate over the array and join the values of firstName and lastName as follows:

let users = [ , , ]; let userFullnames = users.map(function(element) < return `$$`; >) console.log(userFullnames); // ["Susan Steward", "Daniel Longbottom", "Jacob Black"]

The map() method passes more than just an element. Let’s see all arguments passed by map() to the callback function.

Here’s an interactive scrim about using map() to iterate over an array of objects:

The complete map() method syntax

The syntax for the map() method is as follows:

arr.map(function(element, index, array)< >, this);

The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

The this argument will be used inside the callback function. By default, its value is undefined . For example, here’s how to change the this value to the number 80 :

let arr = [2, 3, 5, 7] arr.map(function(element, index, array)< console.log(this) // 80 >, 80);

You can also test the other arguments using console.log() if you’re interested:

let arr = [2, 3, 5, 7] arr.map(function(element, index, array)< console.log(element); console.log(index); console.log(array); return element; >, 80);

Here’s an interactive scrim that goes over the complete syntax:

And that’s all you need to know about the Array.map() method. Most often, you will only use the element argument inside the callback function while ignoring the rest. That’s what I usually do in my daily projects 🙂

Thanks for reading this tutorial

You may also be interested in other JavaScript tutorials that I’ve written, including how to sum an array of objects and methods to find a palindrome string. They are some of the most commonly asked JavaScript problems to solve.

I also have a free newsletter about web development tutorials (mostly JavaScript-related).

Nathan Sebhastian

Nathan Sebhastian

JavaScript Full Stack Developer currently working with fullstack JS using React and Express. Nathan loves to write about his experience in programming to help other people.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Читайте также:  My html page
Оцените статью