-2

I have an array, which is currently grouped like this:

{
  data: [ListingModel, ListingModel, ListingModel, ListingModel, ListingModel, ListingModel]
};

I'd like it to be grouped like this:

{
  groupedData: [
    [ListingModel, ListingModel],
    [ListingModel, ListingModel],
    [ListingModel, ListingModel]
  ]
};
4
  • So you mean to pair them up? Have you tried anything for yourself yet? Please include that Commented Sep 11, 2015 at 9:38
  • If lodash will do then check out the chunk function Commented Sep 11, 2015 at 9:39
  • 1
    How are you deciding which objects are together/paired? Commented Sep 11, 2015 at 9:39
  • 1
    Chunk in underscorejs answered here http://stackoverflow.com/questions/8566667/split-javascript-array-in-chunks-using-underscore-js Commented Sep 11, 2015 at 9:46

4 Answers 4

1

Just loop the input 2 at a time, and create a new array for each pair. This new array then gets added to an overall result array...

var groupedData = [];

for(var i = 0; i < data.length; i+=2){
    groupedData.push([data[i], data[i+1]]);
}

You may want to add validation in the event you have an odd number of elements.

Here is a working example, I just used strings in this example for the ListingModel as you don't define that in your question.

Sign up to request clarification or add additional context in comments.

Comments

1
var group_data = [];

for (var i = 0; i < data.length; i+=2)
{
    var arr = [];
    arr.push(data[i]);
    if ( (i + 1) < data.length)
    {
        arr.push(data[i + 1]);
    }

    group_data.push(arr); //push to main array
}

1 Comment

Could you ask your friends to also upvote my answer please, much appreciated :)
0

u see to change associative array from single array

var data=['ListingModel', 'ListingModel2', 'ListingModel3',   'ListingModel4',' ListingModel5', 'ListingModel6'];
var new_arr = new Array();
for(var i in data){        
if(i < 3){      
    new_arr[i] = [data[i*2],data[i*2+1]];            
}
}
console.log(new_arr); 

Comments

0

If i understand your question, try this.

var data = [1, 2, 3, 4, 5];
    var result = [];
    for (var i = 0, len = data.length / 2; i < len; i++) {
      var two = [];
      
        if (data[2 * i]) {
            two.push(data[2 * i])
        }
        if (data[2 * i+1]) {
            two.push(data[2 * i+1])
        }
      result.push(two);
    }
    console.log(result);//output: [[1, 2], [3, 4], [5]]

2 Comments

Don't reference other answers. In this case it kind of makes yours redundant as you are acknowledging that there is already an answer very similar to yours, so why bother posting your answer at all
Thanks for advice, @musefan. I didn't copy others answer. I tried to find optimum way(faster way).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.