How to convert 1D tensor to regular javascript array?

You can use .dataSync() to get the values of a tensor in a TypedArray and if you want a standard JS array you can use Array.from(), which creates arrays out of array-like objects.

const tensor = tf.tensor1d([1, 2, 3]);
const values = tensor.dataSync();
const arr = Array.from(values);
console.log(values);
console.log(arr);
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]/dist/tf.min.js"></script>

Keep in mind using .dataSync() blocks the UI thread until the values are ready, which can cause performance issues. If you want to load the values asynchronously you can use .data(), which returns a Promise resolving to the TypedArray.


To convert tf.tensor to plain js array there are array() and arraySync() methods.

e.g. tf.tensor([1, 2, 5]).arraySync()