[Vuejs]-How to convert simple array into three-dimensional array (matrix) with Javascript

-1👍

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)

Leave a comment