Wednesday, July 3, 2024
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

Ted Musemwa
As a software developer I’m interested in the intersection of computational thinking and design thinking when solving human problems. As a professional I am guided by the principles of experiential learning; experience, reflect, conceptualise and experiment.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments