首页 > 解决方案 > JavaScript:块方法

问题描述

我正在尝试在 javascript 中实现一个类似于 lodash 块的块函数。似乎我在这里遇到了与计数相关的索引问题,但我无法弄清楚。

// chunk array function breaks an array into chunks of defined size
// [1, 2, 3, 4, 5, 6, 7, 8]
// with size 2
// should output: [[1,2], [3,4], [5,6], [7,8]]
const testArr = [1, 2, 3, 4, 5, 6, 7, 8]
const testArr2 = [1, 2, 3, 4, 5, 6, 7]

function chunk(arr, size){
    let newArr = []
    let tempArr = []

    let iterations;
    let remainder;
    if(Number.isInteger(arr.length / size)){
        iterations = arr.length / size
    } else {
        iterations = size.toString().split('.')[0]
        // how many remain?
        remainder = arr.length % size
    }

    // theres an issue somewhere in here relating to count
    let count = 0
    while(count < iterations){
        tempArr = []
        for(let i = count; i < (size + count); i++){
            tempArr.push(arr[i])
        }
        newArr.push(tempArr)
        count++
    }

    // if(remainder){
    //  for(let i = count; i < count + remainder; i++){
    //      tempArr.push(arr[i])
    //  }
    // }
    return newArr
}

console.log(chunk(testArr, 2))

我对两件不同的事情感兴趣:

  1. 我的代码示例有什么问题?
  2. 您将如何更好地实现这一点?显然我的例子不是很干净,我很好奇其他人会如何处理它(可能是一些 .map .reduce 的东西?)我尝试阅读 lodash 文档,但他们使用了很多内部函数,这让它有点混乱。

实际输出为: [ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ], [ 4, 5 ] ]

输出应该是: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]

谢谢!

标签: javascript

解决方案


一个更简单的方法是:

let size = 2;
[1, 2, 3, 4, 5, 6, 7, 8].reduce((carry, current, index) => {
    // get the current array bucket.  if it doesn't exist, create it.
    let el = carry[Math.floor(index / size)] = carry[Math.floor(index / size)] || [];
    // push the current element onto the current bucket
    el.push(current);
    // return our new array
    return carry;
}, [])

您的代码的问题只是您需要做的:

tempArr.push(arr[i + count])

推荐阅读