Hafiz Ally Lalani Hafiz Ally Lalani - 1 year ago 94
Javascript Question

group by array of array

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]

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download