0

I have an array of float32arrays, and want a function which flattens them into one large float 32array

const first = new Float32Array([1,2]);
const second = new Float32Array([3,4,5]);
const third = new Float32Array([6,7,8,9]);

const chunks = [first,second,third];


//this function should take an array of flaot32arrays 
//and return a new float32array which is the combination of the float32arrays in the input. 
const flattenFloat32 = (chunks) => {
  //Need code for this function
  return 

}

console.log(flattenFloat32(chunks))

2 Answers2

2

Float32Array.of can accept as many arguments as your environment's stack will allow, so you could use:

const result = Float32Array.of(...first, ...second, ...third);

const first = new Float32Array([1,2]);
const second = new Float32Array([3,4,5]);
const third = new Float32Array([6,7,8,9]);

const result = Float32Array.of(...first, ...second, ...third);

console.log(result);

Alternatively, you can use the set function to set elements in a new array from your original, using the lengths of the originsl as the offsets:

const result = new Float32Array(
    first.length + second.length + third.length
);

result.set(first, 0);
result.set(second, first.length);
result.set(third, first.length + second.length);

const first = new Float32Array([1,2]);
const second = new Float32Array([3,4,5]);
const third = new Float32Array([6,7,8,9]);

const result = new Float32Array(
    first.length + second.length + third.length
);

result.set(first, 0);
result.set(second, first.length);
result.set(third, first.length + second.length);

console.log(result);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Ah, I found the solution

const float32Flatten = (chunks) => {
    //get the total number of frames on the new float32array
    const nFrames = chunks.reduce((acc, elem) => acc + elem.length, 0)
    
    //create a new float32 with the correct number of frames
    const result = new Float32Array(nFrames);
    
    //insert each chunk into the new float32array 
    let currentFrame =0
    chunks.forEach((chunk)=> {
        result.set(chunk, currentFrame)
        currentFrame += chunk.length;
    });
    return result;
 }    

const first = new Float32Array([1,2]);
const second = new Float32Array([3,4,5]);
const third = new Float32Array([6,7,8,9]);

const chunks = [first,second,third];
console.log(float32Flatten(chunks))