使用 Lodash 分块分割 JavaScript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8566667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:31:26  来源:igfitidea点击:

Split JavaScript array in chunks using Lodash

javascriptsplitfunctional-programmingunderscore.jslodash

提问by Cesar Canassa

I need to split a JavaScript array into nsized chunks.

我需要将一个 JavaScript 数组拆分成一定n大小的块。

E.g.: Given this array

例如:给定这个数组

["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"]

and a nequals to 4, the output should be this:

并且 an等于 4,输出应该是这样的:

[ ["a1", "a2", "a3", "a4"],
  ["a5", "a6", "a7", "a8"],
  ["a9", "a10", "a11", "a12"],
  ["a13"]
]

I aware of pure JavaScript solutionsfor this problem, but since I am already using LodashI am wondering if Lodash provides a better solution for this.

我知道针对这个问题的纯 JavaScript解决方案,但由于我已经在使用Lodash,我想知道 Lodash 是否为此提供了更好的解决方案。

Edit:

编辑:

I created a jsPerf testto check how much slower the underscore solution is.

我创建了一个jsPerf 测试来检查下划线解决方案的速度有多慢。

回答by Edo

Take a look at lodash' chunk: https://lodash.com/docs#chunk

看看 lodash 的https: //lodash.com/docs#chunk

const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
const chunks = _.chunk(data, 3);
console.log(chunks);
// [
//  ["a1", "a2", "a3"],
//  ["a4", "a5", "a6"],
//  ["a7", "a8", "a9"],
//  ["a10", "a11", "a12"],
//  ["a13"]
// ]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

回答by Chandu

For Underscore based solution try this:

对于基于下划线的解决方案,试试这个:

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

Using the chain wrapper method you can combine the two statements as below:

使用链包装器方法,您可以将两个语句组合如下:

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();

回答by user1009908

A possibly simpler expression:

一个可能更简单的表达:

const coll = [ "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9" ];
const n = 2;
const chunks = _.range(coll.length / n).map(i => coll.slice(i * n, (i + 1) * n));
console.log(chunks);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

回答by user9027325

Underscore supports _.chunk()natively as of version 1.9.0.

Underscore自 1.9.0 版起就支持_.chunk()

const data = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"];
const chunks = _.chunk(data, 4);
console.log(chunks);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>

回答by viacheslav marienko

try this one it is much more practical (for example, if you would want to split the array based on amount of items to be container in each sub array):

试试这个更实用(例如,如果您想根据要在每个子数组中作为容器的项目数量来拆分数组):

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;
};

and the use in your case:

以及在您的情况下的使用:

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

and another case:

还有一个案例:

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