Insert an element into an array.
var insertAt = require( '@stdlib/array/base/insert-at' );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 trueThe function accepts the following arguments:
- x: an input array.
- index: element index.
- value: value to insert.
- 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.
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 );