From 1d array to 2d array in javascript

87 views Asked by At

array [123456789012345678901234567890] result: [[123123123] [456456456] [890890890]]

What is the easiest way to splice an array to get result above. I know how to get: [[1234567890][1234567890][1234567890]]

but not an easy way to get: [[123123123] [456456456] [890890890]]

1

There are 1 answers

0
adelriosantiago On BEST ANSWER

There is a small problem in your data. The output contains no "7" digits. I guess it is an error.

Assuming that the initial data is: [1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9].

And the output: [[1,2,3,1,2,3,1,2,3],[4,5,6,4,5,6,4,5,6],[7,8,9,7,8,9,7,8,9]].

This would do it:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]

arr = arr.reduce((acc, cur, i) => {
  idx = Math.floor((i / 3) % 3)
  acc[idx].push(cur)
  return acc
}, [[], [], []])

console.log("arr", arr)

A few keypoints:

  • Math.floor((i / 3) % 3) obtains the correct index according to the array position.
  • [[], [], []]: This is the initial condition of the accumulator acc. Many people don't know but it can be any object, not necessarily 0 or [].