70

I have Uint8Array instance that contains binary data of some file.
I want to send data to the server, where it will be deserialized as byte[].
But if I send Uint8Array, I have deserialization error.

So, I want to convert it to Array, as Array is deserialized well.
I do it as follows:

    function uint8ArrayToArray(uint8Array) {
        var array = [];

        for (var i = 0; i < uint8Array.byteLength; i++) {
            array[i] = uint8Array[i];
        }

        return array;
    }

This function works fine, but it is not very efficient for big files.

Question: Is there more efficient way to convert Uint8Array --> Array?

2 Answers 2

121

You can use the following in environments that support Array.from already (ES6)

var array = Array.from(uint8Array)

When that is not supported you can use

var array = [].slice.call(uint8Array)
Sign up to request clarification or add additional context in comments.

4 Comments

Yes , [].slice works fine, and it is more compact. But it seems not more efficient. Takes ~5 sec for 10mb file. (
.entries() (and/or .values()) returns ArrayIterator object, not array.
Nitpicking here, but you're just a tiny bit better off calling Array.prototype.slice.call instead of [].slice as it saves an unnecessary array construction.
I just wanna say that even 6 years later this is perfect. My 6 million line file takes just seconds.
-2

There is a method of Uint8Array using the prototype (but it only supported by Firefox and Chrome):

TypedArray.prototype.entries() --> it returns a array.

Check it out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/entries

2 Comments

No, it is ArrayIterator object. Read in link.
Ooo, I see, my mistake ! sorry to don't be helpful for you! Good luck!

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.