TypeScript Array map()
Syntax & Examples
Array.map() method
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Syntax of Array.map()
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.
Parameters
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. |
Return Type
Array.map() returns value of type U[]
.
✐ Examples
1 Using map() to square each number in an array
The map() method can be used to create a new array with the square of each number from the original array.
For example,
- Create an array
arr
with numeric values [1, 2, 3, 4]. - Define a callback function that returns the square of a number.
- Use
map(callbackfn)
to create a new arraysquares
with the squares of each number. - Log the
squares
array to the console.
TypeScript Program
const arr = [1, 2, 3, 4];
const squares = arr.map(x => x * x);
console.log(squares);
Output
[1, 4, 9, 16]
2 Using map() to convert strings to uppercase
The map() method can be used to create a new array with each string from the original array converted to uppercase.
For example,
- Create an array
arr
with string values ['a', 'b', 'c']. - Define a callback function that converts a string to uppercase.
- Use
map(callbackfn)
to create a new arrayupperCaseStrings
with each string converted to uppercase. - Log the
upperCaseStrings
array to the console.
TypeScript Program
const arr = ['a', 'b', 'c'];
const upperCaseStrings = arr.map(str => str.toUpperCase());
console.log(upperCaseStrings);
Output
['A', 'B', 'C']
3 Using map() to extract a property from an array of objects
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,
- Create an array
arr
with objects containingname
andage
properties. - Define a callback function that extracts the
name
property from an object. - Use
map(callbackfn)
to create a new arraynames
with thename
property of each object. - Log the
names
array to the console.
TypeScript Program
const arr = [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }, { name: 'Jim', age: 35 }];
const names = arr.map(person => person.name);
console.log(names);
Output
['John', 'Jane', 'Jim']
Summary
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.