HomeLanguagesJavascriptJavaScript typedArray.subarray() with Examples

JavaScript typedArray.subarray() with Examples

The Javascript typedArray.subarray() is an inbuilt function in JavaScript that is used to return a part of the typedArray object. 

Syntax:

typedarray.subarray(begin, end)

Parameters: It accepts two parameters which are described below:

  • begin: It specifies the index of the starting element from which the part of the given array is to be started. It is optional and inclusive.
  • end: It specifies the index of the ending element up to which the part of the given array is to be included. It is optional and exclusive.

Return value: It returns a new array that is formed from the given typedArray object.

JavaScript examples to show the working of this function:

Example 1: This example shows the basic use of the typedArray.subarray() function. Here it returns the value of the subarray with the given parameters.

javascript




<script>
    // Creating a new typedArray Uint8Array() object
    const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]);
     
    // Calling subarray() functions
    B = A.subarray(1, 3)
    C = A.subarray(1)
    D = A.subarray(3)
    E = A.subarray(0, 6)
    F = A.subarray(0)
         
    // Printing some new typedArray which are
    // the part of the given input typedArray
    console.log(B);
    console.log(C);
    console.log(D);
    console.log(E);
    console.log(F);
</script>


Output:

10,15
10,15,20,25,30,35
20,25,30,35
5,10,15,20,25,30
5,10,15,20,25,30,35

Example 2: When the index is negative then elements get accessed from the end of the typedArray object. Below is the required code which illustrates this negative indexing concept. 

javascript




<script>
    // Creating a new typedArray Uint8Array() object
    const A = new Uint8Array([5, 10, 15, 20, 25, 30, 35 ]);
     
    // Calling subarray() functions
    B = A.subarray(-1)
    C = A.subarray(-2)
    D = A.subarray(-3)
    E = A.subarray(3)
    F = A.subarray(0)
         
    // Printing some new typedArray which are
    // the part of the given input typedArray
    console.log(B);
    console.log(C);
    console.log(D);
    console.log(E);
    console.log(F);
</script>


Output:

35
30,35
25,30,35
20,25,30,35
5,10,15,20,25,30,35
RELATED ARTICLES

Most Popular

Dominic
32711 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7083 POSTS0 COMMENTS
Nicole Veronica
12222 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12307 POSTS0 COMMENTS
Shaida Kate Naidoo
7201 POSTS0 COMMENTS
Ted Musemwa
7463 POSTS0 COMMENTS
Thapelo Manthata
7185 POSTS0 COMMENTS
Umr Jansen
7169 POSTS0 COMMENTS