Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]]
like image 364
Kalashir Avatar asked Jun 27 '16 07:06

Kalashir


People also ask

How do I group an array of objects in JavaScript?

The group() method executes the callbackFn function once for each index of the array, returning a string (or value that can be coerced to a string) indicating the group of the element. A new property and array is created in the result object for each unique group name that is returned by the callback.

What is the use of the group underscore by function?

The _. groupBy() function is used to make collection of the elements in the array passed. It works by matching the value of each element to the other.

How do you create an array of groups?

Steps to create the groupBy function, create an object as initial value for our result object. inside the array reduce, create an array for each distinct key value and push the currentValue if the key value present in the currentValue.


3 Answers

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.

like image 129
Geza Kerecsenyi Avatar answered Oct 11 '22 20:10

Geza Kerecsenyi


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);
like image 16
Avare Kodcu Avatar answered Oct 11 '22 19:10

Avare Kodcu


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>
like image 8
Penny Liu Avatar answered Oct 11 '22 20:10

Penny Liu