How can I merge TypedArrays in JavaScript?

yomotsu picture yomotsu · Dec 28, 2012 · Viewed 28.4k times · Source

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 ].

Answer

Prinzhorn picture Prinzhorn · Dec 28, 2012

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);