gpt4 book ai didi

javascript - JavaScript : chunk method

转载 作者:行者123 更新时间:2023-12-03 01:45:48 26 4
gpt4 key购买 nike

我正在尝试在 JavaScript 中实现一个类似于 lodash chunk 的 block 函数。看来我遇到了与此处计数相关的索引问题,但我无法弄清楚。

// 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 stuff 也许?)我尝试阅读 lodash 文档,但他们使用了很多内部函数,这使得它有点令人困惑。

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

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

谢谢!

最佳答案

更简单的方法是:

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

关于javascript - JavaScript : chunk method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50651719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com