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

时间:2016-06-27 07:49:34

标签: javascript underscore.js

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

var xyz = {"name": ["hi","hello","when","test","then","that","now"]};

输出应低于数组 -

["hi","hello","when"]["test","then","that"]["now"]

7 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:5)

嗨,请参阅此https://plnkr.co/edit/3LBcBoM7UP6BZuOiorKe?p=preview。 for refrence Split javascript array in chunks using underscore.js

使用下划线可以做到

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

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

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

答案 2 :(得分:3)

这可以用lodash chunk覆盖:

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

答案 3 :(得分:1)

您可以使用:

function groupBy(arr, n) {
  var group = [];
  for (var i = 0, end = arr.length / n; i < end; ++i)
    group.push(arr.slice(i * n, (i + 1) * n));
  return group;
}

console.log(groupBy([1, 2, 3, 4, 5, 6, 7, 8], 3));

答案 4 :(得分:0)

这是一个基于curryAvare Kodcu's Answer版本。

function groupBy(groupSize,rtn,item,i)
{
    const j=Math.floor(i/groupSize)

    !rtn[j]?rtn[j]=[item]:
            rtn[j].push(item)

    return rtn
}

arrayOfWords.reduce(curry(groupBy,3),[])

答案 5 :(得分:0)

我遇到了同样的问题,并提出了使用香草js和递归的解决方案

const groupArr = (arr, size) => {
    let testArr = [];
    const createGroup = (arr, size) => {
        // base case
        if (arr.length <= size) {
            testArr.push(arr);
        } else {
            let group = arr.slice(0, size);
            let remainder = arr.slice(size);
            testArr.push(group);
            createGroup(remainder, size);
        }
    }
    createGroup(arr, size);
    return testArr;
}

let data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(groupArr(data, 3));
>>> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

答案 6 :(得分:0)

这是一个简短的解决方案,它绕过.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]]

此外,如果有人正在寻找一种单线的纯JS解决方案,则此库不需要任何库。