TypeScript Array map() Method
Last Updated :
09 Jan, 2025
Improve
The Array.map() is an inbuilt TypeScript function that creates a new array with the results of calling a provided function on every element in the array.
Syntax:
array.map(callback[, thisObject])
Parameters:
This method accepts two parameters as mentioned above and described below:
- callback: This parameter is the function that produces an element of the new Array from an element of the current one.
- thisObject: This is the Object to use as this parameter when executing callback.
Return Value:
This method returns the created array.
Example 1: Applying a Mathematical Function: In this example we creates a number[] array, applies Math.log to each element using map().
// Driver code
let arr: number[] = [11, 89, 23, 7, 98];
// use of map() method
let val: number[] = arr.map(Math.log);
// printing element
console.log(val);
Output:
[
2.3978952727983707,
4.48863636973214,
3.1354942159291497,
1.9459101490553132,
4.584967478670572
]
Example 2: Mapping Elements with Their Indices: In this example we uses map() to iterate over arr, squaring each value. For each element.
// Driver code
let arr: number[] = [2, 5, 6, 3, 8, 9];
// use of map() method
arr.map((val: number, index: number) => {
// printing element
console.log("key: ", index, "value: ", val * val);
});
Output:
key : 0 value : 4
key : 1 value : 25
key : 2 value : 36
key : 3 value : 9
key : 4 value : 64
key : 5 value : 81