javascriptunderscore.js

Group array values in group of 3 objects in each array using underscore.js


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

Output should be below array:

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

Solution

  • Hi please refer this https://plnkr.co/edit/3LBcBoM7UP6BZuOiorKe?p=preview. for refrence Split javascript array in chunks using underscore.js

    using underscore you can do

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

    or

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