使用下划线分组数组项

问题描述 投票:1回答:1

我的数组中有六个项目:[1、2、3、4、5、6]。我想每3个项目将数组项目分组,例如:[[1、2、3],[4、5、6]]。下划线是否可能?

arrays underscore.js
1个回答
0
投票

您可以使用array#reduce对数组元素进行分组。

const arr = [1, 2, 3, 4, 5, 6],
      group = 3,
      result = arr.reduce((r,v,i) => {
        let index = Math.floor(i/group);
        (r[index] = r[index] || [])[i%group] = v;
        return r;
      },[]);
console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.