48

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

4
  • 1
    Why do you need it to be an Array? Commented Oct 6, 2012 at 14:31
  • 2
    Note that the accepted answer works for all of the Javascript Typed Arrays, eg Int8Array, Float64Array, etc. Question title could be changed to reflect this, so it's more helpful for people searching for this answer. Commented Feb 20, 2014 at 17:54
  • I submitted a change proposal to the topic and question formulation. Commented Sep 25, 2014 at 10:57
  • One use case for this would be when you want to modify typed arrays with dat.GUI Commented Jan 2, 2017 at 18:41

4 Answers 4

67

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.

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

1 Comment

Agreed. One can also use the spread syntax in an array literal to achieve the same result. Like: [...new Float32Array(16)].
48

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

var floatarr = new Float32Array(12);
var array =  Array.prototype.slice.call(floatarr);

3 Comments

Join seems to work too, nice trick ! Array.prototype.join.call( floatarr, ',')
Wouldn't this easily exceed the stack size on large arrays?
@JohnWeisz No, floatarr is passed as this.
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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.