JavaScript | typedArray.slice() with Example

The typedArray.slice() is an inbuilt function in JavaScript which is used to return the part of the elements of the given typedArray.

typedArray.slice(begin, end)

Parameters: It takes two parameter which are specified below-

  • begin: It is the beginning index and it can be negative too.
  • end: It is the ending index and here slice extracts elements up to but not including end index.
  • Return value: It returns a new typedArray containing the extracted elements.
    JavaScript code to show the working of this function:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <script>
      
      // Creating some typedArray containing same values
      const A = new Uint8Array([ 5, 10, 15, 20, 25 ]);
      const B = new Uint8Array([ 5, 10, 15, 20, 25 ]);
      const C = new Uint8Array([ 5, 10, 15, 20, 25 ]);
      const D = new Uint8Array([ 5, 10, 15, 20, 25 ]);
      const E = new Uint8Array([ 5, 10, 15, 20, 25 ]);
      const F = new Uint8Array([ 5, 10, 15, 20, 25 ]);
      
      // Calling slice function with starting and ending index
      var a = A.slice(1, 2);
      var b = B.slice(0, 3);
      var c = C.slice(4);
      var d = D.slice(0
        
      // Here index is negative so it extract element
      // from the end of the typedArray
      var e = E.slice(-2);
      var f = F.slice();
      
      // Printing the extracted arrays
      document.write(a +"<br>");
      document.write(b +"<br>");
      document.write(c +"<br>");
      document.write(d +"<br>");
      document.write(e +"<br>");
      document.write(f);
        
    </script>

    chevron_right

    
    

    Output:

    10
    5,10,15
    25
    5,10,15,20,25
    20,25
    5,10,15,20,25


    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.