@stdlib/array-base-to-inserted-at
v0.1.0
Published
Return a new array containing every element from an input array and with a provided value inserted at a specified index.
Readme
toInsertedAt
Return a new array containing every element from an input array and with a provided value inserted at a specified index.
Installation
npm install @stdlib/array-base-to-inserted-atUsage
var toInsertedAt = require( '@stdlib/array-base-to-inserted-at' );toInsertedAt( x, index, value )
Returns a new array containing every element from an input array and with a provided value inserted at a specified index.
var x = [ 1, 2, 3, 4 ];
var out = toInsertedAt( x, 0, 5 );
// returns [ 5, 1, 2, 3, 4 ]
out = toInsertedAt( x, -1, 6 );
// returns [ 1, 2, 3, 4, 6 ]The function accepts the following arguments:
- x: an input array.
- index: element index.
- value: value to insert.
toInsertedAt.assign( x, index, value, out, stride, offset )
Copies elements from one array to another array and inserts a provided value at a specified index.
var x = [ 1, 2, 3, 4 ];
var out = [ 0, 0, 0, 0, 0 ];
var arr = toInsertedAt.assign( x, 0, 5, out, 1, 0 );
// returns [ 5, 1, 2, 3, 4 ]
var bool = ( arr === out );
// returns trueThe function accepts the following arguments:
- x: an input array.
- index: element index.
- value: value to insert.
- out: output array.
- stride: output array stride.
- offset: output array offset.
Notes
- Negative indices are resolved relative to the last array element, with the last element corresponding to
-1.
Examples
var discreteUniform = require( '@stdlib/random-array-discrete-uniform' );
var toInsertedAt = require( '@stdlib/array-base-to-inserted-at' );
// Define an array:
var opts = {
'dtype': 'generic'
};
var x = discreteUniform( 5, -100, 100, opts );
// Define an array containing random index values:
var indices = discreteUniform( 100, -x.length, x.length, opts );
// Define an array with random values to insert:
var values = discreteUniform( indices.length, -10000, 10000, opts );
// Randomly insert elements in the input array:
var i;
for ( i = 0; i < indices.length; i++ ) {
console.log( 'x = [%s]', toInsertedAt( x, indices[ i ], values[ i ] ).join( ',' ) );
}Notice
This package is part of stdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.
For more information on the project, filing bug reports and feature requests, and guidance on how to develop stdlib, see the main project repository.
Community
License
See LICENSE.
Copyright
Copyright © 2016-2026. The Stdlib Authors.
