43

I have a JavaScript Float32Array, and I would like to convert it into a regular JavaScript Array. How can I do this?

Yves M.
  • 29,855
  • 23
  • 108
  • 144
stuax
  • 461
  • 1
  • 6
  • 5

4 Answers4

65

If you don't need to support old browsers (including IE, unfortunately), you can use Array.from, which was added to ES6:

var array = Array.from(floatarr);

This now works in the new releases of every browser (except IE), and it works on all major mobile browsers too.

Cody Piersall
  • 8,312
  • 2
  • 43
  • 57
  • Agreed. One can also use the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) in an array literal to achieve the same result. Like: `[...new Float32Array(16)]`. – Berkant İpek Sep 08 '20 at 10:06
45

Use Array.prototype.slice to convert Float32Array to Array. jsfiddle

var floatarr = new Float32Array(12);
var array =  Array.prototype.slice.call(floatarr);
Yves M.
  • 29,855
  • 23
  • 108
  • 144
Anoop
  • 23,044
  • 10
  • 62
  • 76
1

You can use it as any array, which means you can do this :

var arr = [];
for (var i=0; i<myFloat32array.length; i++) arr[i] = myFloat32array[i];

But it's usually more efficient to use it as a Float32Array instead of converting it.

If you don't want to mix different types of values, don't convert it.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

In one shot:

Object.prototype.toArray=Array.prototype.slice;

Then you can use it this way:

fa32 = new Float32Array([1.0010000467300415, 1.0019999742507935, 2.003000020980835]);
fa64 = new Float64Array([1.0010000467300415, 1.0019999742507935, 2.003000020980835]);

Object.prototype.toArray = Array.prototype.slice

console.log("fa32", fa32.toArray());
console.log("fa64", fa64.toArray());
Zibri
  • 9,096
  • 3
  • 52
  • 44