将数组部分映射到新数组

Ell*_*iot 2 javascript arrays functional-programming

我试图采取一个数组并将其分成长度为4的部分,然后将这些部分推入一个新的数组.我写了一个小脚本来解决它,但我很好奇其他人如何解决这个问题.有没有比我正在做的更好的方式?

var test = ['test0', 'test1', 'test2', 'test3', 'test4', 'test5', 'test6', 'test7' ];

var splitTest = test.map(function(value, index) {
    if (index % 4 === 0) {
          return ([test[index], test[index + 1], test[index + 2], test[index+3]]);
    }
}).filter(function(value) {
    return typeof value != 'undefined';
});
Run Code Online (Sandbox Code Playgroud)

这是我的代码的jsbin:https://jsbin.com/zubavivoto/edit?js,console

输入

["test0", "test1", "test2", "test3", "test4", "test5", "test6", "test7"]
Run Code Online (Sandbox Code Playgroud)

产量

[["test0", "test1", "test2", "test3"], ["test4", "test5", "test6", "test7"]]
Run Code Online (Sandbox Code Playgroud)

Jos*_*ung 7

它不是那么实用,但能完成这项工作

var splitTest = [];
var length = test.length;
for(var i = 0; i < length; i+=4){
  splitTest.push(test.slice(i,Math.min(i+4, length)));
}
Run Code Online (Sandbox Code Playgroud)