Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

README.md

insertAt

Insert an element into an array.

Usage

var insertAt = require( '@stdlib/array/base/insert-at' );

insertAt( x, index, value )

Inserts an element into an array.

var x = [ 1, 1, 2, 3, 3 ];

var y = insertAt( x, -3, 4 );
// returns [ 1, 1, 4, 2, 3, 3 ]

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

The function accepts the following arguments:

  • x: an input array.
  • index: element index.
  • value: value to insert.

Notes

  • Negative indices are resolved relative to the last array element, with the last element corresponding to -1.
  • If provided an out-of-bounds index, the function clamps the index to the beginning or end of the array.
  • The function mutates the input array.

Examples

var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var randi = require( '@stdlib/random/base/discrete-uniform' );
var insertAt = require( '@stdlib/array/base/insert-at' );

// Create an array of random numbers:
var x = discreteUniform( 10, 0, 5, {
    'dtype': 'generic'
});
// returns [...]

console.log( x );

// Insert a random element:
var y = insertAt( x, randi( 0, x.length ), randi( 100, 105 ) );
// returns [...]

console.log( y );