-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]
  ]
};
Julian Mann
  • 6,256
  • 5
  • 31
  • 43
hafiz ali
  • 1,378
  • 1
  • 13
  • 33
  • So you mean to pair them up? Have you tried anything for yourself yet? Please include that – musefan Sep 11 '15 at 09:38
  • If lodash will do then check out the [chunk](https://lodash.com/docs#chunk) function – Gruff Bunny Sep 11 '15 at 09:39
  • 1
    How are you deciding which objects are together/paired? –  Sep 11 '15 at 09:39
  • 1
    Chunk in underscorejs answered here [http://stackoverflow.com/questions/8566667/split-javascript-array-in-chunks-using-underscore-js](http://stackoverflow.com/questions/8566667/split-javascript-array-in-chunks-using-underscore-js) – Nico Vignola Sep 11 '15 at 09:46

4 Answers4

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.

musefan
  • 47,875
  • 21
  • 135
  • 185
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
}
Hardeep Singh
  • 743
  • 1
  • 8
  • 18
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]]
Sherali Turdiyev
  • 1,745
  • 16
  • 29
  • 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 – musefan Sep 11 '15 at 11:11
  • Thanks for advice, @musefan. I didn't copy others answer. I tried to find optimum way(faster way). – Sherali Turdiyev Sep 11 '15 at 11:37
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); 
Jack jdeoel
  • 4,554
  • 5
  • 26
  • 52