0

I have an array filled with Float32Arrays like this:

var arr = [
  new Float32Array([0.3, 0.7, 0.1]),
  new Float32Array([0.2, 0.544, 0.21]),
];

console.log(arr.flat(Infinity));

How do I flatten them to be like this?:

[0.3, 0.7, 0.1, 0.2, 0.544, 0.21]

I have tried use Array.flat(Infinity) but this still leaves the Float32Arrays intact.

pilchard
  • 12,414
  • 5
  • 11
  • 23
little_monkey
  • 401
  • 5
  • 17

3 Answers3

2

For example

let arr = [
  new Float32Array([0.3, 0.7, 0.1]),
  new Float32Array([0.2, 0.544, 0.21]),
];

arr = arr.map(a => [...a]).flat();

console.log(arr);
MikeM
  • 13,156
  • 2
  • 34
  • 47
2

const arr = [ new Float32Array([0.3, 0.7, 0.1]), new Float32Array([0.2, 0.544, 0.21])];

const arr3 =  arr.map(float32Array => Array.from(float32Array));
console.log(arr3.flat()); 
/*
^output
[
  0.30000001192092896,
  0.699999988079071,
  0.10000000149011612,
  0.20000000298023224,
  0.5440000295639038,
  0.20999999344348907
]
*/

//rounded to three decimal points
const arr2 =  arr.map(float32Array => Array.from(float32Array).map(float32 => Math.round(float32 * 1000) / 1000));
console.log(arr2.flat()); //--> [0.3, 0.7, 0.1, 0.2, 0.544, 0.21]
Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26
1

Could do -

var arr = [
  new Float32Array([0.3, 0.7, 0.1]),
  new Float32Array([0.2, 0.544,0.21]),
];

console.log(Array.from(arr[0]).concat(Array.from(arr[1])));
Deon Rich
  • 589
  • 1
  • 4
  • 14