map.md (1898B)
1 <!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. --> 2 3 # Function map 4 5 Create a new matrix or array with the results of a callback function executed on 6 each entry of a given matrix/array. 7 8 For each entry of the input, the callback is invoked with three arguments: 9 the value of the entry, the index at which that entry occurs, and the full 10 matrix/array being traversed. Note that because the matrix/array might be 11 multidimensional, the "index" argument is always an array of numbers giving 12 the index in each dimension. This is true even for vectors: the "index" 13 argument is an array of length 1, rather than simply a number. 14 15 16 ## Syntax 17 18 ```js 19 math.map(x, callback) 20 ``` 21 22 ### Parameters 23 24 Parameter | Type | Description 25 --------- | ---- | ----------- 26 `x` | Matrix | Array | The input to iterate on. 27 `callback` | Function | The function to call (as described above) on each entry of the input 28 29 ### Returns 30 31 Type | Description 32 ---- | ----------- 33 Matrix | array | Transformed map of x; always has the same type and shape as x 34 35 36 ### Throws 37 38 Type | Description 39 ---- | ----------- 40 41 42 ## Examples 43 44 ```js 45 math.map([1, 2, 3], function(value) { 46 return value * value 47 }) // returns [1, 4, 9] 48 49 // The calling convention for the callback can cause subtleties: 50 math.map([1, 2, 3], math.format) 51 // throws TypeError: map attempted to call 'format(1,[0])' but argument 2 of type Array does not match expected type number or function or Object or string or boolean 52 // [This happens because `format` _can_ take a second argument, 53 // but its semantics don't match that of the 2nd argument `map` provides] 54 55 // To avoid this error, use a function that takes exactly the 56 // desired arguments: 57 math.map([1, 2, 3], x => math.format(x)) // returns ['1', '2', '3'] 58 ``` 59 60 61 ## See also 62 63 [filter](filter.md), 64 [forEach](forEach.md), 65 [sort](sort.md)