Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

map

Apply a callback function to elements in an input array and assign results to elements in a new output array.

Usage

var map = require( '@stdlib/array/base/map' );

map( x, fcn[, thisArg] )

Applies a callback function to elements in an input array and assigns results to elements in a new output array.

var naryFunction = require( '@stdlib/utils/nary-function' );
var abs = require( '@stdlib/math/base/special/abs' );

var x = [ -1.0, -2.0, -3.0, -4.0 ];

var y = map( x, naryFunction( abs, 1 ) );
// returns [ 1.0, 2.0, 3.0, 4.0 ]

The function accepts the following arguments:

  • x: input array.
  • fcn: callback function.
  • thisArg: callback execution context (optional).

To set the callback function's execution context, provide a thisArg.

function count( x ) {
    this.count += 1;
    return x;
}

var x = [ 1.0, 2.0, 3.0, 4.0 ];

var ctx = {
    'count': 0
};

var y = map( x, count, ctx );
// returns [ 1.0, 2.0, 3.0, 4.0 ]

var v = ctx.count;
// returns 4

The callback function is provided the following arguments:

  • value: current array element.
  • index: current element index.
  • arr: input array.

map.assign( x, y, stride, offset, fcn[, thisArg] )

Applies a callback function to elements in an input array and assigns results to elements in an output array.

var naryFunction = require( '@stdlib/utils/nary-function' );
var zeros = require( '@stdlib/array/base/zeros' );
var abs = require( '@stdlib/math/base/special/abs' );

var x = [ -1.0, -2.0, -3.0, -4.0 ];

var y = zeros( x.length );

var out = map.assign( x, y, 1, 0, naryFunction( abs, 1 ) );
// returns [ 1.0, 2.0, 3.0, 4.0 ]

var bool = ( out === y );
// returns true

The function accepts the following arguments:

  • x: input array.
  • y: output array.
  • stride: stride length for output array.
  • offset: starting index for output array.
  • fcn: callback function.
  • thisArg: callback execution context (optional).

Notes

  • If provided an array-like object having a map method, the function defers execution to that method and assumes that the method API has the following signature:

    x.map( fcn, thisArg )
    
  • The function supports array-like objects having getter and setter accessors for array element access (e.g., @stdlib/array/base/accessor).

Examples

var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var naryFunction = require( '@stdlib/utils/nary-function' );
var abs = require( '@stdlib/math/base/special/abs' );
var map = require( '@stdlib/array/base/map' );

var x = discreteUniform( 10, -10, 10, {
    'dtype': 'float64'
});

var y = map( x, naryFunction( abs, 1 ) );
console.log( y );