Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

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"]
share|improve this question
    
Do a search for chunk. (NB Lodash has a chunk function) – Gruff Bunny Jun 27 at 7:59
up vote 2 down vote accepted

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();
share|improve this answer
    
That's looks like the same answer given to this question (stackoverflow.com/questions/8566667/…) – Gruff Bunny Jun 27 at 8:01
    
yeah i made reference also – gayathri Jun 27 at 8:02
    
@gayathri : I want to print that group in following structure . Can you help in that ? <ul> <li><span>a1</span><span>a2</span><span>a3</span></li> <li><span>a4</span><span>a5</span><span>a6</span></li> <li><span>a7</span><span>a8</span><span>a9</span></li> </ul> – Kalashir Jun 27 at 9:08
    
check this link i updated plnkr.co/edit/3LBcBoM7UP6BZuOiorKe?p=preview – gayathri Jun 27 at 9:14
    
Instead of cutting and pasting the answer to the other question it would be more relevant to change it so that it applied to the data structure in this question. – Gruff Bunny Jun 27 at 10:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.