Convert a 1D Array into a 2D Array by Specified Length
# Convert a 1D Array into a 2D Array by Specified Length
Convert a one-dimensional array into a two-dimensional array by a specified length.
function pages(arr, len) {
const pages = []
arr.forEach((item, index) => {
const page = Math.floor(index / len)
if (!pages[page]) {
pages[page] = []
}
pages[page].push(item)
})
return pages
}
// Usage
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(pages(arr, 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
console.log(pages(arr, 8)) // [[1, 2, 3, 4, 5, 6, 7, 8], [9]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Use Case Example
As shown in the image, according to the requirements, the number of icons in the icon module is not fixed. Each page displays up to 8 icons, and any beyond 8 are shown on the next page with left-swipe pagination. The provided data is a one-dimensional array, so you can use the code above to convert it into a two-dimensional array with a length of 8, and then render each page accordingly.

<template>
<swiper>
<swiper-slide v-for="(page, index) of pages" :key="index">
<div class="icon" v-for="item of page" :key="item.id">
<div class="icon-img">
<img :src="item.imgUrl">
</div>
<p>{{item.desc}}</p>
</div>
</swiper-slide>
</swiper>
<template>
<script>
...
data () {
return {
iconList: [] // Icon data
}
},
computed: {
pages () {
const pages = []
this.iconList.forEach((item, index) => {
const page = Math.floor(index / 8)
if (!pages[page]) {
pages[page] = []
}
pages[page].push(item)
})
return pages
}
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
Edit (opens new window)
Last Updated: 2026/03/21, 12:14:36