Search code examples
javascripttyped-arrays

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


Solution

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