Skip to content

Files

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Latest commit

5380eca · Mar 3, 2024

History

History

withArray

Return a new array after replacing an index with a given value.

Usage

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

withArray( x, index, value )

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.

Notes

  • 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.

Examples

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);
}