UNB/ CS/ David Bremner/ teaching/ cs2613/ books/ mdn/ Reference/ Global Objects/ TypedArray/ TypedArray.prototype.map()

The map() method of TypedArray instances creates a new typed array populated with the results of calling a provided function on every element in the calling typed array. This method has the same algorithm as Array.prototype.map.

Syntax

map(callbackFn)
map(callbackFn, thisArg)

Parameters

Return value

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

Description

See Array.prototype.map for more details. This method is not generic and can only be called on typed array instances.

Examples

Mapping a typed array to a typed array of square roots

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

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

Mapping a typed 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 to each element of the typed array as map() loops through the original typed array.

const numbers = new Uint8Array([1, 4, 9]);
const doubles = numbers.map((num) => num * 2);
// doubles is now Uint8Array [2, 8, 18]
// numbers is still Uint8Array [1, 4, 9]

Specifications

Browser compatibility

See also