JavasScript:块方法

时间:2018-06-01 22:28:14

标签: javascript

我正在尝试在类似于lodash chunk的javascript中实现一个chunk函数。好像我在这里遇到一个与计数相关的索引问题,但我无法弄明白。

// 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文档,但他们使用了很多内部函数,使它有点混乱。
  3. 实际输出为:[[1,2],[2,3],[3,4],[4,5]]

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

    谢谢!

1 个答案:

答案 0 :(得分:1)

更简单的方法是:

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])