简体   繁体   中英

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

Pure javascript code:

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

Here's a short and simple solution abusing the fact that .push always returns 1 (and 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]]

Plus, this one requires no libraries, in case someone is looking for a one-liner pure-JS solution.

This can be covered by 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>

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

You may use:

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

Here's a curry -able version that builds off Avare 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),[])

I ran into this same problem and came up with solution using vanilla js and recursion

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]]

Here is another simple oneliner, quite similar to the solution of gtournie .

  1. We create an array of the desired length array.length / n .
  2. This array needs to be filled to get map to work.
  3. We map portions of the initial array to the new array elements.
const group = (array, n) => 
  new Array(Math.ceil(array.length / n))
    .fill(undefined)
    .map((el, i) => array.slice(i * n, (i + 1) * n));
var xyz = {"name": ["hi","hello","when","test","then","that","now"]};
group(xyz.name, 3)

gives

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM