Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge TypedArrays in JavaScript?

I'd like to merge multiple arraybuffers to create a Blob. however, as you know, TypedArray dosen't have "push" or useful methods...

E.g.:

var a = new Int8Array( [ 1, 2, 3 ] ); var b = new Int8Array( [ 4, 5, 6 ] ); 

As a result, I'd like to get [ 1, 2, 3, 4, 5, 6 ].

like image 411
yomotsu Avatar asked Dec 28 '12 15:12

yomotsu


People also ask

How do I merge Uint8Array?

You can use the set method. Create a new typed array with all the sizes. Example: var arrayOne = new Uint8Array([2,4,8]); var arrayTwo = new Uint8Array([16,32,64]); var mergedArray = new Uint8Array(arrayOne.

What is JavaScript ArrayBuffer?

The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".

What is JavaScript Typedarray?

JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.

What is the use of Uint8Array?

The Uint8Array() constructor creates a typed array of 8-bit unsigned integers. The contents are initialized to 0 . Once established, you can reference elements in the array using the object's methods, or using standard array index syntax (that is, using bracket notation).


2 Answers

Use the set method. But note, that you now need twice the memory!

var a = new Int8Array( [ 1, 2, 3 ] ); var b = new Int8Array( [ 4, 5, 6 ] );  var c = new Int8Array(a.length + b.length); c.set(a); c.set(b, a.length);  console.log(a); console.log(b); console.log(c); 
like image 176
Prinzhorn Avatar answered Oct 06 '22 00:10

Prinzhorn


for client-side ~ok solution:

const a = new Int8Array( [ 1, 2, 3 ] ) const b = new Int8Array( [ 4, 5, 6 ] ) const c = Int8Array.from([...a, ...b]) 
like image 38
JerryCauser Avatar answered Oct 06 '22 01:10

JerryCauser