我有一个如下数组:
var someArray = ['val1','val2','val3','val4','val5','val6','val7','val8','val9','val10','val11','val12'];
我正试图找出一些优雅的方法,使用underscore
,简单地将其转换为如此数组的数组......
[['val1','val2','val3','val4'], ['val5','val6','val7','val8'], ['val9','val10','val11','val12']]
其中新数组的每个索引都是来自第一个数组的四个元素的组。使用underscore.js
是否有一种简单优雅的方式。
答案 0 :(得分:12)
下划线,因为您问过:(Example)
var i = 4, list = _.groupBy(someArray, function(a, b){
return Math.floor(b/i);
});
newArray = _.toArray(list);
Vanilla JS:(Example)
var newArray = [], size = 4;
while (someArray.length > 0) newArray.push(someArray.splice(0, size));
答案 1 :(得分:4)
纯JavaScript解决方案,使用splice()
:
Object.defineProperty( Array.prototype, 'eachConsecutive', {
value:function(n){
var copy = this.concat(), result = [];
while (copy.length) result.push( copy.splice(0,n) );
return result;
}
});
var someArray = ['val1','val2','val3','val4','val5','val6','val7','val8','val9','val10','val11','val12'];
var chunked = someArray.eachConsecutive(4);
//-> [["val1","val2","val3","val4"],["val5","val6","val7","val8"],["val9","val10","val11","val12"]]