llamahahn
llamahahn

Reputation: 11

Converting this 3d array into 2d array in javascript

I am trying to convert the following 3D array into a 2D array. Currently, my data has the following structure.

[ [[0,0,345], [1,0,555], ... [9,0,333]], ... [[0,9,1000], [1,9,987], ... [9,9,129]] ]

into

[[0,0,345], [1,0,355], ... [9,0,333], [0,1,1000], [1,1,987], ... [9,9,129]]

so the first element contains a width value, and the second is the height value. The third value will be a random value from 0 to 1023.

As you see, the width and height will be 10 each. And I am trying to get rid of the outermost array.

I have tried to iterate for each row to bounce to a new array using push, but keep getting undesired forms. Any help will be appreciated!

Upvotes: 0

Views: 363

Answers (2)

Ork Sophanin
Ork Sophanin

Reputation: 146

you can try this flatmap. Example below.

let data = [[["creative fee (example)"], [1000]], [["Item 1...", "Item 2..."], [600, 1000]], [["Item 3...", "Item 4..."], [400, 600]]],
    result = data.flatMap(([l, r]) => l.map((v, i) => [v, r[i]]));

console.log(result);

Upvotes: 0

Unmitigated
Unmitigated

Reputation: 89224

You can directly use Array#flat.

const arr = [ [[0,0,345], [1,0,555], [9,0,333]],  [[0,9,1000], [1,9,987], [9,9,129]] ];
const res = arr.flat();
console.log(JSON.stringify(res));

Upvotes: 1

Related Questions