Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I merge an array of Uint8Arrays?

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.

like image 375
Marko Nikolov Avatar asked Mar 06 '18 11:03

Marko Nikolov


2 Answers

Just treat it like any normal array:

var concatArray = new Uint8Array([ ...Uint8Array1, ...Uint8Array2, ...Uint8Array3 ]);
like image 62
Neil Avatar answered Oct 23 '22 10:10

Neil


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);
like image 35
Dominik Avatar answered Oct 23 '22 11:10

Dominik