使用underscore.js将每个数组中3个对象组中的数组值分组

Kal*_*hir 4 javascript underscore.js

下面是一个数组,我必须在每个对象中分组3个值

var xyz = {"name": ["hi","hello","when","test","then","that","now"]};
Run Code Online (Sandbox Code Playgroud)

输出应低于数组 -

["hi","hello","when"]["test","then","that"]["now"]
Run Code Online (Sandbox Code Playgroud)

Ava*_*dcu 11

纯JavaScript代码:

function groupArr(data, n) {
    var group = [];
?
    for (var i = 0, j = 0; i < data.length; i++) {
        if (i >= n && i % n === 0)
            j++;
        group[j] = group[j] || [];
        group[j].push(data[i])
    }
?
    return group;
}

groupArr([1,2,3,4,5,6,7,8,9,10,11,12], 3);
Run Code Online (Sandbox Code Playgroud)


Gez*_*nyi 8

这是一个简短而简单的解决方案,它滥用了.push总是返回1(和1 == true)的事实:

const arr = [0, 1, 2, 3, 4, 5, 6]
const n = 3

arr.reduce((r, e, i) =>
    (i % n ? r[r.length - 1].push(e) : r.push([e])) && r
, []); // => [[0, 1, 2], [3, 4, 5], [6]]
Run Code Online (Sandbox Code Playgroud)

另外,这个不需要库,以防有人正在寻找单行纯 JS 解决方案。

  • 这是一个聪明且非常有用的解决方案,可以用作表达式,甚至可以使用它来格式化具有千位分隔符的货币,当反转时, r.push([e]) 变为 r.push([',',e]) ;) (2认同)

Pen*_*Liu 6

这可以被 lodash 覆盖_.chunk

var xyz = {"name": ["hi","hello","when","test","then","that","now"]},size = 3;
console.log(_.chunk(xyz.name, size));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Run Code Online (Sandbox Code Playgroud)


Gay*_*han 3

嗨,请参阅此https://plnkr.co/edit/3LBcBoM7UP6BZuOiorKe?p=preview.for refrence 使用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);
Run Code Online (Sandbox Code Playgroud)

要么

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

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();
Run Code Online (Sandbox Code Playgroud)