Imagine I have an array:
DATA = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13 ,14 ,15 ,16, 17, 18, 19, 20, 21, 22, 23];
And I want it to convert into 3-dimensional Array((Matrix of ROW x COLUMN)x SET by Number of Instances, like this:
A = [[1, 2, 3], [4, 5, 6],[7, 8, 9];
B = [[10, 11, 12], [13, 14, 15], [16, 17, 18]];
C = [[19, 20, 21], [22,23]]
Note, that rows and columns of the matrix are changeable. Meaning that the number of items in the rows or column may change and even the amount of items in the data set may also differ.
I want to be able iterate through those sets of arrays into sets that a contained within particular defined classes when they are created.
EXPECTED RESULT: (GENERATED TABLE includes html structure):
<CONTAINER>
//A SET
<div class "set">
ROW 1: <row><div class "items"> 1 </div><div class "items"> 2</div><div class "items"> 3</div></row>
ROW 2: <row><div class "items"> 4</div><div class "items"> 5</div><div class "items"> 6</div><row>
ROW 3: <row><div class "items"> 7</div><div class "items"> 8</div><div class "items"> 9</div></row>
</div>
</div>
//B SET
<div class "set">
ROW 1: <row><div class "items"> 10</div><div class "items"> 11</div><div class "items"> 12</div></row>
ROW 2: <row><div class "items"> 13</div><div class "items"> 14</div><div class "items"> 15</div><row>
ROW 3: <row><div class "items"> 16</div><div class "items"> 17</div><div class "items"> 18</div></row>
</div>
</div>
//C Set
<div class "set">
ROW 1: <row><div class "items"> 19</div><div class "items"> 20</div><div class "items"> 21</div></row>
ROW 2: <row><div class "items"> 22</div><div class "items"> 23</div></row>
</div>
</div>
</CONTAINER>
Solution to this question can be found here: Vue.js - How to convert a simple array to dynamic NxNxN Matrix
This is transforming to 3d array
const chunk = (arr, number) => {
const chunked = arr.reduce((res, value, ind) => {
if (ind % number === 0) {
res.push([])
}
res[res.length - 1].push(value)
return res
}, [])
const last = chunked[chunked.length - 1]
let empty = last[last.length - 1]
if (Array.isArray(empty)) {
empty = new Array(empty.length).fill(null)
} else {
empty = null
}
while(last.length < number) last.push(empty)
return chunked
}
const _2d = chunk([7, 4, 2, 3, 9], 2)
console.log(_2d)
const _3d = chunk(_2d, 2)
console.log(_3d)
A generic NxNxN[..xNxNxN... etc] - not NxM - but your example is 3x3x3 anyway
let articles = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16, 17, 18, 19, 20, 21, 22, 23); let num = 3; function articleGroups(a, num, dim) { let each = num ** (dim - 1) let required = each * num; a.length = required; return Array.from({length:num}, () => a.splice(0, each)).slice().map(a => (dim > 2)? articleGroups(a, num, dim - 1): a); } console.log(articleGroups(articles, num, 3));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.