简体   繁体   English

javascript中从一维数组到二维数组

[英]From 1d array to 2d array in javascript

array [123456789012345678901234567890] result: [[123123123] [456456456] [890890890]]数组 [123456789012345678901234567890] 结果:[[123123123] [456456456] [890890890]]

What is the easiest way to splice an array to get result above.拼接数组以获得上述结果的最简单方法是什么。 I know how to get: [[1234567890][1234567890][1234567890]]我知道如何获得:[[1234567890][1234567890][1234567890]]

but not an easy way to get: [[123123123] [456456456] [890890890]]但不是一个简单的方法:[[123123123] [456456456] [890890890]]

There is a small problem in your data.你的数据有一个小问题。 The output contains no "7" digits.输出不包含“7”位数字。 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] .假设初始数据为: [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]] .和输出: [[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. Math.floor((i / 3) % 3)根据数组位置获取正确的索引。
  • [[], [], []] : This is the initial condition of the accumulator acc . [[], [], []] :这是累加器acc的初始条件。 Many people don't know but it can be any object, not necessarily 0 or [] .很多人不知道,但它可以是任何对象,不一定是0[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM