使用 underscore.js 将每个数组中 3 个对象的组中的数组值分组 [英] Group array values in group of 3 objects in each array using underscore.js
本文介绍了使用 underscore.js 将每个数组中 3 个对象的组中的数组值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是一个数组,我必须在其中对每个对象中的 3 个值进行分组
Below is an array in which I have to group 3 values in each object
var xyz = {"name": ["hi","hello","when","test","then","that","now"]};
输出应低于数组 -
[["hi","hello","when"],["test","then","that"],["now"]]
推荐答案
请参考这个 https://plnkr.co/edit/3LBcBoM7UP6BZuOiorKe?p=preview.参考 使用 underscore.js 将 javascript 数组分割成块
使用下划线就可以了
JS
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();
这篇关于使用 underscore.js 将每个数组中 3 个对象的组中的数组值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文