JavaScript | Unit16Array.from() Method

The Uint16Array array represents an array of 16-bit unsigned integers in the platform byte order. By default, the contents of Uint16Array are initialized to 0.
The Uint16Array.from() function is used to create a new Uint16Array from an array-like or iterable object. So when you want to convert an arrayLike or iterable object then you can be used this function by passing the object as a parameter to this function along with map function and value used for map function if needed.

Syntax:

Uint16Array.from( source, mapFn, thisArg )

Parameters: This method accept three parameters as mentioned above and described below.

  • source: This parameter is an array-like or iterable object which is used to convert to an Uint16Array object.
  • mapFn: This parameter is optional which is Map function to call on every element of the Uint16Array array.
  • thisArg: This parameter is optional which is value to use as this when executing mapFn.

Return Value: This method returns a new Uint16Array instance.

Below examples illustrate the Unit16Array.from() Method in JavaScript:



Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
// Create a Uint16Array from a string
// like structure
var  array = Uint16Array.from('543234543');
  
// Print the result
document.write(array);
</script>

chevron_right


Output:

5, 4, 3, 2, 3, 4, 5, 4, 3

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
  
// Create a Uint16Array from a array 
// multiplying 3 to each number
// using function
var  array = Uint16Array.from([32, 
       53, 122, 434, 213], z => z*3);
  
// Print the result
document.write(array);
</script>

chevron_right


Output:

96, 159, 366, 1302, 639

References: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/from#

full-stack-img

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.