3

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))

3
  • Make a new array whose size is the sum of the other array sizes, then copy the values. Commented Feb 17, 2021 at 13:43
  • Does this answer for you? stackoverflow.com/questions/14071463/… Commented Feb 17, 2021 at 13:46
  • @Watanabe.N - Good find. Commented Feb 17, 2021 at 13:47

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.