使用underscore.js分块JavaScript数组
我需要将一个JavaScript数组分成n
大小的块。
例如:给定这个数组
["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]
而一个n
等于4,输出应该是这样的:
[ ["a1", "a2", "a3", "a4"], ["a5", "a6", "a7", "a8"], ["a9", "a10", "a11", "a12"], ["a13"] ]
我知道这个问题的纯JavaScript 解决scheme ,但由于我已经使用underscore.js我想知道如果下划线提供了一个更好的解决scheme。
编辑:
我创build了一个jsPerftesting来检查下划线解决scheme的速度。
看看lodash的块 : https ://lodash.com/docs#chunk
var data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]; _.chunk(data, 3); // [ // ["a1", "a2", "a3"], // ["a4", "a5", "a6"], // ["a7", "a8", "a9"], // ["a10", "a11", "a12"], // ["a13"] // ]
对于基于Underscore的解决scheme,试试这个:
var data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]; var n = 3; var lists = _.groupBy(data, function(element, index){ return Math.floor(index/n); }); lists = _.toArray(lists); //Added this to convert the returned object to an array. console.log(lists);
使用链式包装器的方法,你可以结合两个陈述如下:
var data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]; var n = 3; var lists = _.chain(data).groupBy(function(element, index){ return Math.floor(index/n); }).toArray() .value();
一个可能更简单的expression:
_.range(coll.length / n).map(i => coll.slice(i * n, (i + 1) * n))
尝试这一个它是更实际的(例如,如果你想分裂的数量的基础上项目的容量在每个子arrays):
function chunk(arr, start, amount){ var result = [], i, start = start || 0, amount = amount || 500, len = arr.length; do { //console.log('appending ', start, '-', start + amount, 'of ', len, '.'); result.push(arr.slice(start, start+amount)); start += amount; } while (start< len); return result; };
并在你的情况下使用:
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17], chunked = chunk(arr, 0, Math.floor(arr.length/3)); //to get 4 nested arrays console.log(chunked);
另一个案例:
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17], chunked = chunk(arr, 0, 3); // to get 6 nested arrays each containing maximum of 3 items console.log(chunked);