Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork0
Convert an array to an object supporting fancy indexing.
License
stdlib-js/array-to-fancy
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
About stdlib...
We believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we've built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.
The library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.
When you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.
To join us in bringing numerical computing to the web, get started by checking us out onGitHub, and please considerfinancially supporting stdlib. We greatly appreciate your continued support!
Convert an array to an object supporting fancy indexing.
An array supportingfancy indexing is an array which supports slicing via indexing expressions for both retrieval and assignment.
vararray2fancy=require('@stdlib/array-to-fancy');// Create a plain array:varx=[1,2,3,4,5,6,7,8];// Turn the plain array into a "fancy" array:vary=array2fancy(x);// Select the first three elements:varv=y[':3'];// returns [ 1, 2, 3 ]// Select every other element, starting from the second element:v=y['1::2'];// returns [ 2, 4, 6, 8 ]// Select every other element, in reverse order, starting with the last element:v=y['::-2'];// returns [ 8, 6, 4, 2 ]// Set all elements to the same value:y[':']=9;// Create a shallow copy by selecting all elements:v=y[':'];// returns [ 9, 9, 9, 9, 9, 9, 9, 9 ]
npm install @stdlib/array-to-fancy
Alternatively,
- To load the package in a website via a
scripttag without installation and bundlers, use theES Module available on theesmbranch (seeREADME). - If you are using Deno, visit the
denobranch (seeREADME for usage intructions). - For use in Observable, or in browser/node environments, use theUniversal Module Definition (UMD) build available on the
umdbranch (seeREADME).
Thebranches.md file summarizes the available branches and displays a diagram illustrating their relationships.
To view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.
vararray2fancy=require('@stdlib/array-to-fancy');
Converts an array to an object supporting fancy indexing.
varSlice=require('@stdlib/slice-ctor');varx=[1,2,3,4];vary=array2fancy(x);// returns <Array>// Normal element access:varv=y[0];// returns 1v=y[1];// returns 2// Using negative integers:v=y[-1];// returns 4v=y[-2];// returns 3// Using subsequence expressions:v=y['1::2'];// returns [ 2, 4 ]// Using Slice objects:v=y[newSlice(1,null,2)];// returns [ 2, 4 ]// Assignment:y['1:3']=5;v=y[':'];// returns [ 1, 5, 5, 4 ]
The function supports the following options:
cache: cache for resolving array index objects. Must have a
getmethod which accepts a single argument: a string identifier associated with an array index.If an array index associated with a provided identifier exists, the
getmethod should return an object having the following properties:- data: the underlying index array.
- type: the index type. Must be either
'mask','bool', or'int'. - dtype: thedata type of the underlying array.
If an array index is not associated with a provided identifier, the
getmethod should returnnull.Default:
ArrayIndex.strict: boolean indicating whether to enforce strict bounds checking. Default:
false.
By default, the function returns a fancy array which doesnot enforce strict bounds checking. For example,
vary=array2fancy([1,2,3,4]);varv=y[10];// returns undefined
To enforce strict bounds checking, set thestrict option totrue.
vary=array2fancy([1,2,3,4],{'strict':true});varv=y[10];// throws <RangeError>
Returns a function for converting an array to an object supporting fancy indexing.
varfcn=array2fancy.factory();varx=[1,2,3,4];vary=fcn(x);// returns <Array>varv=y[':'];// returns [ 1, 2, 3, 4 ]
The function supports the following options:
cache: default cache for resolving array index objects. Must have a
getmethod which accepts a single argument: a string identifier associated with an array index.If an array index associated with a provided identifier exists, the
getmethod should return an object having the following properties:- data: the underlying index array.
- type: the index type. Must be either
'mask','bool', or'int'. - dtype: thedata type of the underlying array.
If an array index is not associated with a provided identifier, the
getmethod should returnnull.Default:
ArrayIndex.strict: boolean indicating whether to enforce strict bounds checking by default. Default:
false.
By default, the function returns a function which, by default, doesnot enforce strict bounds checking. For example,
varfcn=array2fancy.factory();vary=fcn([1,2,3,4]);varv=y[10];// returns undefined
To enforce strict bounds checking by default, set thestrict option totrue.
varfcn=array2fancy.factory({'strict':true});vary=fcn([1,2,3,4]);varv=y[10];// throws <RangeError>
The returned function supports the same options as above. When the returned function is provided option values, those values override the factory method defaults.
Wraps a provided array as an array index object.
varx=[1,2,3,4];varidx=array2fancy.idx(x);// returns <ArrayIndex>
For documentation and usage, seeArrayIndex.
- A fancy array shares thesame data as the provided input array. Hence, any mutations to the returned array will affect the underlying input array and vice versa.
- For operations returning a new array (e.g., when slicing or invoking an instance method), a fancy array returns a new fancy array having the same configuration as specified by
options. - A fancy array supports indexing using positive and negative integers (both numeric literals and strings),
Sliceinstances,subsequence expressions, andindex arrays (boolean, mask, and integer). - A fancy array supports all properties and methods of the input array, and, thus, a fancy array can be consumed by any API which supports array-like objects.
- Indexing expressions provide a convenient and powerful means for creating and operating on array views; however, their use does entail a performance cost. Indexing expressions are best suited for interactive use (e.g., in theREPL) and scripting. For performance critical applications, prefer equivalent functional APIs supporting array-like objects.
- In older JavaScript environments which donot support
Proxyobjects, the use of indexing expressions isnot supported.
By default, fancy arrays donot enforce strict bounds checking across index expressions. The motivation for the default fancy array behavior stems from a desire to maintain parity with plain arrays; namely, the returning ofundefined when accessing a single non-existent property.
Accordingly, whenstrict isfalse, one may observe the following behaviors:
varx=array2fancy([1,2,3,4],{'strict':false});// Access a non-existent property:varv=x['foo'];// returns undefined// Access an out-of-bounds index:v=x[10];// returns undefinedv=x[-10];// returns undefined// Access an out-of-bounds slice:v=x['10:'];// returns []// Access one or more out-of-bounds indices:vari=array2fancy.idx([10,20]);v=x[i];// throws <RangeError>
Whenstrict istrue, fancy arrays normalize index behavior and consistently enforce strict bounds checking.
varx=array2fancy([1,2,3,4],{'strict':true});// Access a non-existent property:varv=x['foo'];// returns undefined// Access an out-of-bounds index:v=x[10];// throws <RangeError>v=x[-10];// throws <RangeError>// Access an out-of-bounds slice:v=x['10:'];// throws <RangeError>// Access one or more out-of-bounds indices:vari=array2fancy.idx([10,20]);v=x[i];// throws <RangeError>
Fancy arrays supportbroadcasting in which assigned scalars and single-element arrays are repeated (without additional memory allocation) to match the length of a target array instance.
vary=array2fancy([1,2,3,4]);// Broadcast a scalar:y[':']=5;varv=y[':'];// returns [ 5, 5, 5, 5 ]// Broadcast a single-element array:y[':']=[6];v=y[':'];// returns [ 6, 6, 6, 6 ]
Fancy array broadcasting follows thesame rules as forndarrays. Consequently, when assigning arrays to slices, the array on the right-hand-side must be broadcast-compatible with number of elements in the slice. For example, each assignment expression in the following example follows broadcast rules and is thus valid.
vary=array2fancy([1,2,3,4]);y[':']=[5,6,7,8];varv=y[':'];// returns [ 5, 6, 7, 8 ]y['1::2']=[9,10];v=y[':'];// returns [ 5, 9, 7, 10 ]y['1::2']=[11];v=y[':'];// returns [ 5, 11, 7, 11 ]y['1::2']=12;v=y[':'];// returns [ 5, 12, 7, 12 ]// Out-of-bounds slices (i.e., slices with zero elements):y['10:20']=[13];v=y[':'];// returns [ 5, 12, 7, 12 ]y['10:20']=13;v=y[':'];// returns [ 5, 12, 7, 12 ]y['10:20']=[];v=y[':'];// returns [ 5, 12, 7, 12 ]
However, the following assignment expressions are not valid.
vary=array2fancy([1,2,3,4]);y[':']=[5,6];// throws <Error>// Out-of-bounds slice (i.e., a slice with zero elements):y['10:20']=[8,9,10,11];// throws <Error>
In order to broadcast a nested array element as one would a scalar, one must wrap the element in a single-element array.
vary=array2fancy([[1,2],[3,4]]);// Assign individual array elements:y[':']=[5,6];varv=y[':'];// returns [ 5, 6 ]y=array2fancy([[1,2],[3,4]]);// Broadcast a nested array:y[':']=[[5,6]];v=y[':'];// returns [ [ 5, 6 ], [ 5, 6 ] ]
Fancy arrays support(mostly) safe casts (i.e., any cast which can be performed without overflow or loss of precision, with the exception of floating-point arrays which are also allowed to downcast from higher precision to lower precision).
varUint8Array=require('@stdlib/array-uint8');varInt32Array=require('@stdlib/array-int32');varx=newInt32Array([1,2,3,4]);vary=array2fancy(x);// 8-bit unsigned integer values can be safely cast to 32-bit signed integer values:y[':']=newUint8Array([5,6,7,8]);
When attempting to perform an unsafe cast, fancy arrays will raise an exception.
varUint8Array=require('@stdlib/array-uint8');varx=newUint8Array([1,2,3,4]);vary=array2fancy(x);// Attempt to assign a non-integer value:y[':']=3.14;// throws <TypeError>// Attempt to assign a negative value:y[':']=-3;// throws <TypeError>
When assigning a real-valued scalar to a complex number array (e.g.,Complex128Array orComplex64Array), a fancy array will cast the real-valued scalar to a complex number argument having an imaginary component equal to zero.
varComplex128Array=require('@stdlib/array-complex128');varreal=require('@stdlib/complex-float64-real');varimag=require('@stdlib/complex-float64-imag');varx=newComplex128Array([1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0]);vary=array2fancy(x);// Retrieve the first element:varv=y[0];// returns <Complex128>varre=real(v);// returns 1.0varim=imag(v);// returns 2.0// Assign a real-valued scalar to the first element:y[0]=9.0;v=y[0];// returns <Complex128>re=real(v);// returns 9.0im=imag(v);// returns 0.0
varUint8Array=require('@stdlib/array-uint8');varInt32Array=require('@stdlib/array-int32');varBooleanArray=require('@stdlib/array-bool');vararray2fancy=require('@stdlib/array-to-fancy');varx=[1,2,3,4,5,6];vary=array2fancy(x);// returns <Array>// Slice retrieval:varz=y['1::2'];// returns [ 2, 4, 6 ]z=y['-2::-2'];// returns [ 5, 3, 1 ]z=y['1:4'];// returns [ 2, 3, 4 ]// Slice assignment:y['4:1:-1']=10;z=y[':'];// returns [ 1, 2, 10, 10, 10, 6 ]y['2:5']=[-10,-9,-8];z=y[':'];// returns [ 1, 2, -10, -9, -8, 6 ]// Array index retrieval:varidx=array2fancy.idx;vari=idx([1,3,4]);// integer index arrayz=y[i];// returns [ 2, -9, -8 ]i=idx([true,false,false,true,true,true]);// boolean arrayz=y[i];// returns [ 1, -9, -8, 6 ]i=idx(newBooleanArray([true,false,false,true,true,true]));// boolean arrayz=y[i];// returns [ 1, -9, -8, 6 ]i=idx(newUint8Array([0,0,1,0,0,1]));// mask arrayz=y[i];// returns [ 1, 2, -9, -8 ]i=idx(newInt32Array([0,0,1,1,2,2]));// integer index arrayz=y[i];// returns [ 1, 1, 2, 2, -10, -10 ]// Array index assignment:x=[1,2,3,4,5,6];y=array2fancy(x);i=idx([true,false,true,false,true,false]);// boolean arrayy[i]=5;z=y[':'];// returns [ 5, 2, 5, 4, 5, 6 ]i=idx(newBooleanArray([true,false,true,false,true,false]));// boolean arrayy[i]=7;z=y[':'];// returns [ 7, 2, 7, 4, 7, 6 ]i=idx(newUint8Array([1,1,1,0,0,0]));// mask arrayy[i]=8;z=y[':'];// returns [ 7, 2, 7, 8, 8, 8 ]i=idx(newInt32Array([5,3,2]));// integer index arrayy[i]=[9,10,11];z=y[':'];// returns [ 7, 2, 11, 10, 8, 9 ]i=idx([0,1]);// integer index arrayy[i]=-1;z=y[':'];// returns [ -1, -1, 11, 10, 8, 9 ]
@stdlib/array-slice:return a shallow copy of a portion of an array.@stdlib/ndarray-fancy:fancy multidimensional array constructor.
This package is part ofstdlib, 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 developstdlib, see the main projectrepository.
SeeLICENSE.
Copyright © 2016-2025. The StdlibAuthors.
About
Convert an array to an object supporting fancy indexing.
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.