Search code examples
javascriptarraysmultidimensional-arrayflatten

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?

-EDIT- Bottom line: I need it to return a regular Array object, like the starting one not typed.


Solution

  • 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));
    }, []));
    

    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.