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"]]
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.
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.
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.
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.
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);
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With