How to flatten a clamped array
If enc
is an Array
of Uint8ClampedArray
s, this one-liner statement should work:
var flattened = Uint8ClampedArray.from(enc.reduce((a, b) => [...a, ...b], []));
This is equivalent to:
var flattened = Uint8ClampedArray.from(enc.reduce(function(a, b){ return Array.from(a).concat(Array.from(b));}, []));
To answer your actual question as to why reduce
didn’t work for you:
[].concat(Uint8ClampedArray([1, 2, 3, 4]));
unfortunately doesn’t return [1, 2, 3, 4]
but [Uint8ClampedArray[4]]
. concat
doesn’t work with Typed Arrays.
I would calculate the total length first and then use set
. The advantage of set
is
If the source array is a typed array, the two arrays may share the same underlying ArrayBuffer; the browser will intelligently copy the source range of the buffer to the destination range.
function flatten(arrays, TypedArray) { var arr = new TypedArray(arrays.reduce((n, a) => n + a.length, 0)); var i = 0; arrays.forEach(a => { arr.set(a,i); i += a.length; }); return arr;}console.log(flatten( [new Uint8ClampedArray([1,2,3]), new Uint8ClampedArray([4,5,6])], Uint8ClampedArray));
An alternative is using blobs, as proposed by guest271314. The proper way would be
function flatten(arrays, TypedArray, callback) { var reader = new FileReader(); reader.onload = () => { callback(new TypedArray(reader.result)); }; reader.readAsArrayBuffer(new Blob(arrays));}flatten( [new Uint8ClampedArray([1,2,3]), new Uint8ClampedArray([4,5,6])], Uint8ClampedArray, result => console.log(result));
Checking the MDN, TypedArray
s doesn't share quite a few normal JS array functions.
You can collect the values from the clamped array, and initialize a new one like this however:
var enc = [Uint8ClampedArray.of(1, 2), Uint8ClampedArray.of(4, 8), Uint8ClampedArray.of(16, 32)]var flattened = Uint8ClampedArray.from(enc.reduce(function(acc, uintc){ Array.prototype.push.apply(acc, uintc) return acc;}, []));console.log(flattened); // [object Uint8ClampedArray]console.log(flattened.join(',')); // "1,2,4,8,16,32"