简体   繁体   English

使用javascript将单个数组转换为多维数组

[英]Turn a single array into a multidimensional array with javascript

I came across an exercise that wants me to write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array.我遇到了一个练习,它希望我编写一个函数,将数组(第一个参数)分成大小长度(第二个参数)的组,并将它们作为多维数组返回。 Here is the starter code that is provided.这是提供的入门代码。

function chunk(arr, size) {
  // Break it up.
  return arr;
}

chunk(['a', 'b', 'c', 'd'], 2);

so in this particular case, the returned array should be [[a,b],[c,d]].所以在这种特殊情况下,返回的数组应该是 [[a,b],[c,d]]。 I have tried using array.slice, and array.splice, and array.push but I get nothing even close to being the right answer.我曾尝试使用 array.slice、array.splice 和 array.push,但我什至没有得到接近正确答案的结果。 If anybody can help shed some light on this issue, I would be very appreciative.如果有人能帮助阐明这个问题,我将不胜感激。 I have been stuck on this for days and it's getting really frustrating.我已经被困在这个问题上好几天了,这真的很令人沮丧。 Thanks.谢谢。

Not the best code I've ever written but here you go:不是我写过的最好的代码,但你去吧:

function chunk(arr, size) {
    mda = []    
    for (i = 0; i+size < arr.length; i = i + size) { 
        mda.push(arr.slice(i,i+size));
    }
         mda.push(arr.slice(i));
    return mda
}
chunk(['a', 'b', 'c', 'd'], 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM