Marco Valente Marco Valente - 3 months ago 12
Javascript Question

How to flatten a clamped array

At the minute I find myself stuck trying to flatten a Uint8ClampedArray.

The starting array structure is

data = [227, 138, 255…]
and after creating an array from that of the like
enc = [Uint8ClampedArray[900], Uint8ClampedArray[900], Uint8ClampedArray[900]...]
I try to flatten it.

I tried many methods / solutions for that but no one seems to work:

the MDN suggested method

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
return a.concat(b);
}, []);

with concat

data = [].concat.apply([], enc);

and through a function

function flatten(arr) {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);

but no joy so far, it keeps returning the array as it is. Anyone can point me in the right direction and explain why is that?


If enc is an Array of Uint8ClampedArrays, 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));
}, []));