The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
The syntax of Array.map() method is:
map<U>(callbackfn: function, thisArg?: any): U[]
This map() method of Array calls a defined callback function on each element of an array, and returns an array that contains the results.
Parameter | Optional/Required | Description |
---|---|---|
callbackfn | required | A function that is called for every element of the array. Each time callbackfn executes, the returned value is added to the new array. |
thisArg | optional | Value to use as this when executing callbackfn. |
Array.map() returns value of type U[]
.
The map() method can be used to create a new array with the square of each number from the original array.
For example,
arr
with numeric values [1, 2, 3, 4].map(callbackfn)
to create a new array squares
with the squares of each number.squares
array to the console.const arr = [1, 2, 3, 4];
const squares = arr.map(x => x * x);
console.log(squares);
[1, 4, 9, 16]
The map() method can be used to create a new array with each string from the original array converted to uppercase.
For example,
arr
with string values ['a', 'b', 'c'].map(callbackfn)
to create a new array upperCaseStrings
with each string converted to uppercase.upperCaseStrings
array to the console.const arr = ['a', 'b', 'c'];
const upperCaseStrings = arr.map(str => str.toUpperCase());
console.log(upperCaseStrings);
['A', 'B', 'C']
The map() method can be used to create a new array with a specific property extracted from each object in the original array.
For example,
arr
with objects containing name
and age
properties.name
property from an object.map(callbackfn)
to create a new array names
with the name
property of each object.names
array to the console.const arr = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Jim', age: 35 }];
const names = arr.map(person => person.name);
console.log(names);
['John', 'Jane', 'Jim']
In this TypeScript tutorial, we learned about map() method of Array: the syntax and few working examples with output and detailed explanation for each example.