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

ParameterOptional/RequiredDescription
callbackfnrequiredA function that is called for every element of the array. Each time callbackfn executes, the returned value is added to the new array.
thisArgoptionalValue 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,

  1. Create an array arr with numeric values [1, 2, 3, 4].
  2. Define a callback function that returns the square of a number.
  3. Use map(callbackfn) to create a new array squares with the squares of each number.
  4. 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,

  1. Create an array arr with string values ['a', 'b', 'c'].
  2. Define a callback function that converts a string to uppercase.
  3. Use map(callbackfn) to create a new array upperCaseStrings with each string converted to uppercase.
  4. 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,

  1. Create an array arr with objects containing name and age properties.
  2. Define a callback function that extracts the name property from an object.
  3. Use map(callbackfn) to create a new array names with the name property of each object.
  4. 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.