Return a new array after replacing an index with a given value.
var withArray = require( '@stdlib/array/base/with' );
Return a new array after updating an index into the input array.
var x = [ 1, 2, 3, 4 ];
var out = withArray( x, 0, 5 );
// returns [5, 2, 3, 4]
out = withArray( x, -1, 6 );
// returns [1, 2, 3, 6]
The function accepts the following arguments:
- x: an input array.
- index: element index.
- value: replacement value.
-
If provided an array-like object having a
with
method, the function defers execution to that method and assumes that the method has the following signature:x.with( index, value )
If provided an array-like object without a
with
method, the function manually shallow copied that object and assign provided value to that index. -
Negative indices are resolved relative to the last array element, with the last element corresponding to
-1
. -
If provided out-of-bounds indices, the function always returns
undefined
.
var discreteuniform = require( '@stdlib/random/array/discrete-uniform' );
var withArray = require( '@stdlib/array/base/with' );
var rand = require( '@stdlib/random/base/randu' );
var x;
var indices;
// Define an array:
x = discreteuniform( 10, -100, 100 );
// Define an array containing random index values:
indices = discreteuniform( 100, -x.length, x.length-1 );
// Randomly selected values from the input array:
var i;
var index;
var newvalue;
var updatedarray;
for (i = 0; i < indices.length; i++) {
index = indices[i];
newvalue = rand(); // Random value between -100 and 100
updatedarray = withArray(x, index, newvalue); // Update the value at the given index
console.log('Updated x[%d] to %d', index, newvalue);
console.log('Updated array:', updatedarray);
}