Convert a one-dimensional array into a two-dimensional array according to the specified length

Without further ado, let’s get straight to the code…

  var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] //定义的到数组
  function Array(arr, len) {    //arr:要改造的数组   len:指定的长度
    const Array = []
    arr.forEach((item, index) => {
      const page = Math.floor(index / len)
      if (!Array[page]) {
        Array[page] = []
      }
      Array[page].push(item)
    })
    return Array
  }

  // 使用
  console.log(Array(arr, 3)) // [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  console.log(Array(arr, 6)) // [[1, 2, 3, 4, 5, 6, 7, 8], [9]]

Guess you like

Origin blog.csdn.net/m0_63873004/article/details/126706100