little_monkey
little_monkey

Reputation: 439

How to flatten a Float32Array in JS?

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.

Upvotes: 0

Views: 719

Answers (3)

Rukshan Jayasekara
Rukshan Jayasekara

Reputation: 1985

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]

Upvotes: 2

Deon Rich
Deon Rich

Reputation: 659

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

Upvotes: 1

MikeM
MikeM

Reputation: 13631

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

Upvotes: 2

Related Questions