I have an array of several Uint8Arrays. Something similar to this:
[Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(16384), Uint8Array(8868)]
How do I merge/concatenate/join (not sure what the right term is) them to a single ArrayBuffer?
The key here is that the output I need must be an ArrayBuffer.
Just treat it like any normal array:
var concatArray = new Uint8Array([ ...Uint8Array1, ...Uint8Array2, ...Uint8Array3 ]);
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.length + arrayTwo.length);
mergedArray.set(arrayOne);
mergedArray.set(arrayTwo, arrayOne.length);
Alternative: Convert your typed array in "normal" arrays. concat it and create a type array of it again.
In your case (solution):
let myArrays = [new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(16384), new Uint8Array(8868)];
// Get the total length of all arrays.
let length = 0;
myArrays.forEach(item => {
length += item.length;
});
// Create a new array with total length and merge all source arrays.
let mergedArray = new Uint8Array(length);
let offset = 0;
myArrays.forEach(item => {
mergedArray.set(item, offset);
offset += item.length;
});
// Should print an array with length 90788 (5x 16384 + 8868 your source arrays)
console.log(mergedArray);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With