JavaScript | typedArray.subarray() with Examples

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

typedarray.subarray(begin, end)

Parameters: It accepts two parameters which are described below:

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

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

JavaScript code to show the working of this function:

Code #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<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
   document.write(B +"<br>");
   document.write(C +"<br>");
   document.write(D +"<br>");
   document.write(E +"<br>");
   document.write(F +"<br>");
  
</script>

chevron_right


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

Code #2:
When index are in negative then elements get accessed from the end of the typedArray object.

Below is the required code which illustrates this negative indexing concept.

filter_none

edit
close

play_arrow

link
brightness_4
code

<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
   document.write(B +"<br>");
   document.write(C +"<br>");
   document.write(D +"<br>");
   document.write(E +"<br>");
   document.write(F +"<br>");
  
</script>

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.